1. 程式人生 > >leetcode: 7. Reverse Integer

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;檢查 } }