Tuesday, July 15, 2014

Reverse Integer

Reverse digits of an integer.


Example1: x = 123, return 321
Example2: x = -123, return -321

把一个整数reverse,需要考虑两点:1. 判断数的正负  2. 反转是否会溢出。对于第二点,我用long作为函数类型,这样排除了溢出的可能性。
public class Solution {
    //Time: O(num of digits in x)  Space: O(1)
    public long reverse(int x) {
        boolean isNeg = false;
        if (x < 0) {
            x = -x;
            isNeg = true;
        }
        long res = 0;
        while (x > 0) {
            res = res * 10 + x % 10;
            x /= 10;
        }
        if (isNeg) {
            res = -res;
        }
        return res;
    }
}

No comments:

Post a Comment