C# program to check if binary representation is palindrome

CsharpServer Side ProgrammingProgramming

To check for palindrome, let us say our number is 5, whose 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 &amp; 1) == 1)
         myRev ^= 1;
      num >>= 1;
   }
   return myRev;
}

Then the actual representation will be compared be the reverse one by returning and getting the value from the funcReverse() function −

public static bool checkPalindrome(long num) {
   long myRev = funcReverse(num);
   return (num == myRev);
}

Example

The following is the complete example to check if the binary representation of a number is palindrome −

Live Demo

using System;
public class Demo {
   public static long funcReverse(long num) {
      long myRev = 0;
      while (num > 0) {
         myRev <<= 1;
         if ((num &amp; 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");
   }
}

Output

Palindrome Number
raja
Published on 24-Jul-2018 09:31:00
Advertisements