
要检查回文数,假设我们的数字是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中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号