[LeetCode]009. Palindrome Number

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.


Solution:

Because we cannot use the extra space, so we can try the math method: refer to the 007. reverse Integer.

calculate the first digit and the last digit of the integer, compare them,

if first == last, then discount them from the original number, (the result must divide 10 here)

must consider each special cases here!


下面的代码尚未来得及pass OJ,先行记录下来,LeetCode 服务器挂掉了~

以下代码已pass OJ, 需要注意对count的处理,保证首尾数字每次各向内缩进1位, count / 100



public class Solution {
    public boolean isPalindrome(int x) {
        // Start typing your Java solution below
        // DO NOT write main() function
        if(x<0){
            return false;
        }
        int first = 0;
        int last = 0;
        int temp = x;
        int count = 1;
        while(temp >= 10){
            temp = temp/10;
            count *= 10;
        }
        while(x>=0){
            if(x<10){
                return true;
            }else if(x==10){
                return false;
            }
            last = x % 10;
            first = x / count;
            if(first == last){
                x = (x - first*count - last) / 10;
                count = count / 100;
                //must deal with the count!  10022001
            }else{
                return false;
            }
        }
        return false;
    }
}


2015-04-06 update: python solution

数学解法,首先比较数字左右两端,然后去掉头尾数字继续比较。

class Solution:
    # @return a boolean
    def isPalindrome(self, x):
        if x < 0:
            return False
        len = 0
        temp = x
        while temp > 0:
            len += 1
            temp /= 10
        while x >= 0 and len > 0:
            left = x / (pow(10, len-1))
            right = x % 10
            if left != right:
                return False
            x = (x - left * pow(10, len-1))/10
            len -= 2
        if 0 <= x < 10:
            return True



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值