leetcode: 7. Reverse Integer

Difficulty

Easy

Description

/**
 * Given a 32-bit signed integer, reverse digits of an integer.
 * Example 1:
 * Input: 123
 * Output: 321
 * 
 * Example 2:
 * Input: -123
 * Output: -321
 * 
 * Example 3:
 * Input: 120
 * Output: 21
 *
 */

Solution

Time Complexity: O(log(x))
Space Complexity: O(1)

class Solution {
    public int reverse(int x) {
		int ret = 0;
		while(x != 0) { 
		    //检查是否溢出
            if (ret > Integer.MAX_VALUE/10 || (ret == Integer.MAX_VALUE/10 && x % 10 > 7)) return 0;
            if (ret < Integer.MIN_VALUE/10 || (ret == Integer.MIN_VALUE/10 && x % 10 < -8)) return 0;
			ret = ret * 10 + x % 10;
			x /= 10;
		}
        return ret;   //或使用 return (int)ret == ret ? (int)ret : 0;检查
    }
}

猜你喜欢

转载自blog.csdn.net/baidu_25104885/article/details/85240114