Java程序检查二进制表示形式是否是回文
回文是向前和向后都相同的序列。检查数字的二进制表示形式是回文,但不考虑前导0。一个例子如下:
Number = 5 Binary representation = 101
5的二进制表示形式是回文,因为向前和向后都相同。
演示该程序的程序如下。
示例
public class Example {
public static void main(String argc[]) {
long num = 5, n1;
long reverse = 0;
n1 = num;
while (n1 > 0) {
reverse <<= 1;
if ((n1 & 1) == 1)
reverse ^= 1;
n1 >>= 1;
}
if(num == reverse) {
System.out.println("Binary representation of " + num + " is palindrome");
}else {
System.out.println("Binary representation of " + num + " is not palindrome");
}
}
}输出结果
Binary representation of 5 is palindrome
现在让我们了解上面的程序。
给定数字5的倒数是使用while循环获得的。证明这一点的代码片段如下-
long num = 5, n1;
long reverse = 0;
n1 = num;
while (n1 > 0) {
reverse <<= 1;
if ((n1 & 1) == 1)
reverse ^= 1;
n1 >>= 1;
}如果数字与其反数相同,则为回文并打印,否则为非回文并打印。证明这一点的代码片段如下所示-
if(num == reverse) {
System.out.println("Binary representation of " + num + " is palindrome");
}else {
System.out.println("Binary representation of " + num + " is not palindrome");
}热门推荐
1 带狗狗训练
4 听力训练狗狗
6 怎训练狗狗
7 腹肌训练狗狗
8 网球训练狗狗
9 记叙文训练狗狗
10 狗狗太凶怎么训练
11 核心力量训练狗狗
12 狗狗乱叫怎么训练
13 发音训练狗狗
14 怎么训练狗狗叼东西给主人
15 荆州训练狗狗
16 篮球训练狗狗
17 做训练狗狗
18 训练狗狗坐姿