【LeetCode】Palindrome Number

来源:互联网 发布:数据字典和数据流程图 编辑:程序博客网 时间:2024/06/05 01:55

Determine whether an integer is a palindrome. Do this without extra space.

Some hints:

Could negative integers be palindromes? (ie, -1)

If you are thinking of converting the integer to string, note the restriction of using extra space.

You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case?

There is a more generic way of solving this problem.

这一题主要的条件是不用额外的存储空间,因此我们不能把数字转换为字符串进行处理。而最直观的思路,就是分别比较最高位和最低位的数,然后紧接着比较次高位和次低位,最后直到所有的数字都比较完。

但是我们要注意两个问题:1、负数肯定不满足;2、如果数字的位数为奇数个,到最后肯定会只剩下中间一个数字,需要进行处理。

在网上看到一个代码,看上去是没有问题的,它会每次比较并去掉最高位和最低位,并通过判断当前处理的数字是否大于9,来确定该数字是否只剩下1位。如果只有1位,就不用继续比较,返回正确就行了;如果大于1位,需要继续执行循环。

public boolean isPalindrome(int x) {    if (x < 0) {    return false;    }    int div = 1;    while (x / 10 >= div) {        div *= 10;    }    while (x > 9) {        int high = x / div;        int low = x % 10;        if (high != low) {            return false;        }        x = (x % div) / 10;        div /= 100;    }    return true;}
但是,该代码不能处理10000021这样的特例,因为我们第一个循环中,div=10000000,在执行完该循环后x=2,div=100000,可以发现,x中间的那些0都被忽略掉了,最后判断这个数为true,明显是不对的。

因此,我们对x > 9的判断条件进行了修正,用x != 0来做判断,多进行一次循环处理。对于x中间不包含0的情况,例如1234321,最后一个循环里,x=4,div=10,得到的high和low相等,依然不影响我们的结果;对于x中间包含0的情况,例如10000021,第二个循环中high=x / div = 2 / 100000 = 0,与low不相同,可以解决前面出现的错误情况。

public boolean isPalindrome(int x) {    if (x < 0) {    return false;    }    int div = 1;    while (x / 10 >= div) {        div *= 10;    }    while (x != 0) {        int high = x / div;        int low = x % 10;        if (high != low) {            return false;        }        x = (x % div) / 10;        div /= 100;    }    return true;}
转载请注明出处:http://blog.csdn.net/sunset108/article/details/35779041

0 0