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

王林
Release: 2023-09-13 11:21:08
forward
1299 people have browsed it

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

To check the palindrome number, suppose our number is 5, its binary is −

101
Copy after login

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;
}
Copy after login

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);
}
Copy after login

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");
   }
}
Copy after login

Output

Palindrome Number
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template