LeetCode 7. Reverse Integer

LeetCode 7. Reverse Integer

原题链接在这里:https://leetcode.com/problems/reverse-integer/

题目:

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

Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231,  231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

题解:

x%10加到res中.

负数-123 mod 10 = -3, 所以不用担心负数.

注意corner case, e.g. 2133....99, 反过来9开头时就冒了Integer.MAX_VALUE了.

Time Complexity: O(n), n是x的位数. Space: O(1).

AC Java:

public class Solution {
    public int reverse(int x) {
        long res = 0;
        while(x != 0){
            res = res*10 + x%10;
            x /= 10;
        }
        
        if(res > Integer.MAX_VALUE || res < Integer.MIN_VALUE){
            return 0;
        }
        
        return (int)res;
    }
}

类似Reverse Bits.