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
現在讓我們瞭解以上程式。
使用while迴圈獲得給定數字5的反轉。演示此功能的程式碼片段如下所示:
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");
}
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP