要檢查回文數,假設我們的數字是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中文網其他相關文章!