尝试用两头分别比较的方法,结果发现无法解决1000021这种问题
1 public class Solution {
2 public boolean isPalindrome(int x) {
3 if(x<0) return false;
4 int lastbit=x%10;
5 int firstbit;
6 int num=x;
7 int bits=0;
8 while(num/10!=0){
9 num=num/10;
10 bits++;
11 }
12 firstbit=num;
13 if(firstbit!=lastbit) return false;
14 else{
15 x=x-firstbit*((int)(Math.pow(10,bits)));
16 x=x/10;
17 if(x==0) return true;
18 else return isPalindrome(x);
19 }
20 }
21 }
查看了论坛的解答,看到一个很好的solution, 它怎么想到13行的
div/=100的,给跪了,这样刚好解决了中间有0的问题,比如1021会被判定为false, 而121会被判定为true。 解答详见:http://leetcode.com/2012/01/palindrome-number.html
1 public class Solution {
2 public boolean isPalindrome(int x) {
3 if (x < 0) return false;
4 int div = 1;
5 while (x / div >= 10) {
6 div *= 10;
7 }
8 while (x != 0) {
9 int l = x / div;
10 int r = x % 10;
11 if (l != r) return false;
12 x = (x % div) / 10;
13 div /= 100;
14 }
15 return true;
16 }
17 }
时间: 2024-07-29 10:12:56