
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check if Binary Representation is Palindrome in C#
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 & 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 −
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"); } }
Output
Palindrome Number
Advertisements