7. Reverse Integer

Reverse digits of an integer.
Example1: x = 123, return 321Example2: x = -123, return -321
click to show spoilers.
**Note:
**The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.

Overflow判断方法见http://www.jianshu.com/p/07f7e7a2dd3d

Solution:

思路: basic
Time Complexity: O(length) Space Complexity: O(1)

Solution Code:

class Solution {
    public int reverse(int x) {
        int sign = x >= 0 ? 1 : -1;
        
        int result = 0;
        while(x != 0) {
            int last_digit = x % 10;
            x = x / 10;
            
            if(sign > 0 && result > ((Integer.MAX_VALUE - last_digit) / 10)) {
                // overflow
                return 0;
            }
            else if(sign < 0 && result < (Integer.MIN_VALUE - last_digit) / 10) {
                // overflow
                return 0;
            } 
            
            result *= 10;
            result += last_digit; 
            
              
        }
        return result;
    }
}

你可能感兴趣的:(7. Reverse Integer)