9. Palindrome Number

题目:

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

click to show spoilers.

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.

链接: http://leetcode.com/problems/palindrome-number/

题解:

可以用除法和模运算rebuild一个结果,然后比较和输入是否相等。这里其实有可能会overflow,就是在 result * 10的时候,但越界的话也会返回一个32位整数,这个整数是 result * 10结果转换为64位里面的low 32位,一般来说与输入不同。所以结果返回false,也能过AC,但是不严谨。

Time Complexity - O(logx), Space Complexity - O(1)。

public class Solution {

    public boolean isPalindrome(int x) {

        if(x == 0)

            return true;

        int result = 0, temp = x;    

        

        while(temp > 0){

            result = 10 * result + temp % 10;

            temp /= 10;

        }

        

        return result == x;

    }

}

 

另外一种方法可以避免overflow。先用对数计算出x有几位,然后通过数学运算比较第一位和最后一位是否相等,接下来去掉最大的一位和最小的一位,再将digitNum - 2,继续进行计算。

Time Complexity - O(logx), Space Complexity - O(1)。

public class Solution {

    public boolean isPalindrome(int x) {

        if(x < 0)

            return false;

        int digitNum= (int)(Math.log(x) / Math.log(10));    

        int left = 0, right = 0;

        

        while(x > 0){

            int powInTens = (int)Math.pow(10, digitNum);

            left = x / powInTens;

            right = x % 10;

            if(left != right)

                return false;

            x -= left * powInTens;

            x /= 10;

            digitNum -= 2 ;

        }

        

        return true;

    }

}

测试:

 

你可能感兴趣的:(number)