为了检查回文,让我们说我们的数字是5,其二进制数是-
101
101的回文数为101,要检查您需要使用以下功能反转位。在这里,使用按位左移和按位右移运算符-
public static long funcReverse(long num) { long myRev = 0; while (num > 0) { myRev <<= 1; if ((num & 1) == 1) myRev ^= 1; num >>= 1; } return myRev; }
然后通过返回并从funcReverse()
函数中获取值,将实际表示与反向表示进行比较-
public static bool checkPalindrome(long num) { long myRev = funcReverse(num); return (num == myRev); }
以下是检查数字的二进制表示是否为回文式的完整示例-
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() { //二进制值为5 us 101- long num = 5; if (checkPalindrome(num)) Console.WriteLine("Palindrome Number"); else Console.WriteLine("Not a Palindrome Number"); } }
输出结果
Palindrome Number