To check the palindrome number, suppose our number is 5, its binary is −
101
The palindrome of 101 is 101 and to check you need to reverse the bits using the following function. Here, bitwise left and bitwise right shift operators are used −
public static long funcReverse(long num) { long myRev = 0; while (num > 0) { myRev <<= 1; if ((num & 1) == 1) myRev ^= 1; num >>= 1; } return myRev; }
The actual representation is then compared with the reverse representation by returning and getting the value from the funcReverse() function−
public static bool checkPalindrome(long num) { long myRev = funcReverse(num); return (num == myRev); }
The following is a complete example for checking whether the binary representation of a number is a palindrome −
Online demonstration
using System; public class Demo { public static long funcReverse(long num) { long myRev = 0; while (num > 0) { myRev <<= 1; if ((num & 1) == 1) myRev ^= 1; num >>= 1; } return myRev; } public static bool checkPalindrome(long num) { long myRev = funcReverse(num); return (num == myRev); } public static void Main() { // Binary value of 5 us 101 long num = 5; if (checkPalindrome(num)) Console.WriteLine("Palindrome Number"); else Console.WriteLine("Not a Palindrome Number"); } }
Palindrome Number
The above is the detailed content of C# program to check if a binary representation is a palindrome. For more information, please follow other related articles on the PHP Chinese website!