Home >Backend Development >C#.Net Tutorial >C# program to check if a binary representation is a palindrome

C# program to check if a binary representation is a palindrome

王林
王林forward
2023-09-13 11:21:081338browse

检查二进制表示形式是否回文的 C# 程序

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 &amp; 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);
}

Example

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 &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

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete