January 19, 2019

7. Reverse Integer

7. Reverse Integer

每次把最后一位取出来,放到结果的第一位;把倒数第二位取出来,放到结果的第二位…,以此类推。取数用 “当前数%10”,放进去用 “结果*10 + 取出的值”。
考虑两种情况:负数,overflow。

Java Solution

class Solution {
    public int reverse(int x) {
        int rev = 0;
        while (x != 0) { // applies to both positive and negative numbers
            int newRev = rev * 10 + x % 10;
            if ( (newRev - x % 10) / 10 != rev) {
                return 0;  // Handles overflow
            }
            rev = newRev;
            x /= 10;
        }
        return rev;
    }
}

Python Solution

Python 取余和想象中不一样。。参见这篇文章。所以不能直接用上面的方法做。

comments powered by Disqus