アルゴリズム-leetcode-毎日の問題-一つの整数が回文かどうかを判断します.

950 ワード

**Example 1:Input:121 Output:true
Example 2:Input:-121 Output:false Explanion:From left to right,it reads-121.From right to left,it becompes 121-.The refore it is not a palindrome.
Example 3:Input:10 Output:false Explannation:Reads 01 from right to left.The refore it is not a palindrome.*.
解析:負の数と10の倍数は必ず回文ではないことが分かります.また、回文は直接二つのポインタで前の一つを使うと判断されますが、この方法は最適ではありません.整数の各ビットを遍歴する必要はないので、逆さま整数と同じように、回文と逆さま整数を見たら、必ず残りと割り算を思い出します.
    public static boolean isPalindrome(int x) {
        if(x < 0 || (x!=0 && x%10 == 0)) {
            return false;
        }
        int sum = 0;
        while (x > sum) {
            //               
            //     , x < sum,x       sum,          
            //     ,       ,   ,x == sum,     ,            
            sum = sum * 10 + x % 10; //sum    
            x = x / 10;              //x    
        }
        return (x == sum) || (x == sum/10);
    }