s******d 发帖数: 61 | 1 可以像这样通过以为来做吗?还是%10比较好,还有其他什么更好的方法吗?
public static boolean judgepalidrom(int num){
char[] ch=new char[Integer.size];
for(int i=0;i
char[Integer.size-i-1]=(char)((num>>i)&1+'0');
}
String str=new String(ch);
for(int j=0;j
if(str[j]!=str[str.length()-j-1])
return false;
}
return true;
}
|
i*****r 发帖数: 265 | 2 You can revert a binary number in logn time (n being the number of bits of
your integer, like 32-bit integer). Then you can compare if the reverted one
is the same as origin. |
s******d 发帖数: 61 | 3 How to revert a binary number in logn time?
Thanks!!! |
d*******d 发帖数: 2050 | 4 coask
【在 s******d 的大作中提到】 : How to revert a binary number in logn time? : Thanks!!!
|
s**x 发帖数: 405 | 5 bool judge(int num){
if (num < 0) return false;
int x, y;
for (x = num, y = 0; x; x >>= 1)
y = (y << 1) | (x & 1);
return (y == num);
} |
w*******s 发帖数: 96 | 6 check num = 00100100(binary) in your case:
you will only get y = 001001.
It looks ugly, but should work.
bool judge(int num){
if (num < 0) return false;
int i, x, y;
int bitsize = sizeof(num)*8;
for (i = 0, x = num, y = 0; i< bitsize ; x >>= 1,i++)
y = (y << 1) | (x & 1);
return (y == num);
} |
i**********e 发帖数: 1145 | |
g**********y 发帖数: 14569 | 8 他这个不用形成那个反转数,只用判断是不是回文就行,简单code (对32-bit):
boolean isPalindrome(int n) {
for (int i=0; i<16; i++) {
if ((n>>i) != (n>>(31-i))) return false;
}
return true;
}
【在 i**********e 的大作中提到】 : Hint: use XOR.
|
s**x 发帖数: 405 | 9 waveletus, it seems our interpretation of the problem is different
my view is that binary encoding of integers always start with '1' bits.
for example 00100100 should just be 100100.
100100 should be false.
10101 should be true.
【在 w*******s 的大作中提到】 : check num = 00100100(binary) in your case: : you will only get y = 001001. : It looks ugly, but should work. : bool judge(int num){ : if (num < 0) return false; : int i, x, y; : int bitsize = sizeof(num)*8; : for (i = 0, x = num, y = 0; i< bitsize ; x >>= 1,i++) : y = (y << 1) | (x & 1); : return (y == num);
|