要检查回文数,假设我们的数字是5,其二进制为−
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; }
然后通过从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() { // Binary value of 5 us 101 long num = 5; if (checkPalindrome(num)) Console.WriteLine("Palindrome Number"); else Console.WriteLine("Not a Palindrome Number"); } }
Palindrome Number
以上是检查二进制表示形式是否回文的 C# 程序的详细内容。更多信息请关注PHP中文网其他相关文章!