題目地址:
https://www.lintcode.com/problem/palindrome-number-ii/description
給定一個非負整數,判斷其二進制表示是否迴文。直接算其二進制翻轉後的數,看一下是否與原數相等即可。代碼如下:
public class Solution {
/**
* @param n: non-negative integer n.
* @return: return whether a binary representation of a non-negative integer n is a palindrome.
*/
public boolean isPalindrome(int n) {
// Write your code here
int m = n;
int rev = 0;
while (m != 0) {
rev <<= 1;
rev += m & 1;
m >>= 1;
}
return rev == n;
}
}
時空複雜度()。