palindrome number

1. Question

确定一个数是否是回文数。要求不使用额外空间。

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

2. Solution

如果是负数,就不是回文数。

2.1 reverse integer

采用反转整数的方法,注意处理溢出(采用long存储数据)

public class Solution {
    public boolean isPalindrome(int x) {
        if( x < 0 )
            return false;
        long rev = 0;
        int y = x;
        while( y != 0 ){
            rev = rev * 10 + y % 10;
            y = y / 10;
        }
        if( rev == (long)x )
            return true;
        return false;
    }
}
View Code

2.2 整除取余计算

结合采用整除取余,同时从数的两端开始计算来判断(需要先确定位数)

public class Solution {
    public boolean isPalindrome(int x) {
        if( x < 0 )
            return false;
        int bits = 1;
        for( int y=x/10; y!=0; y/=10,bits++ );
        for( int i=1; i<=bits/2; i++ ){
            if( ( ( x / (int)Math.pow( 10, bits-i ) ) % 10 )  != ( ( x / (int)Math.pow( 10, i-1 ) ) % 10 ) )
                return false;
        }
        return true;
    }
}
View Code

3. 复杂度

O(n)

原文地址:https://www.cnblogs.com/hf-cherish/p/4596321.html