7. Reverse Integer

发布时间 2023-07-20 23:29:57作者: xiaoyongyong
7. Reverse Integer
Medium

Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0.

Assume the environment does not allow you to store 64-bit integers (signed or unsigned).

Example 1:

Input: x = 123
Output: 321

Example 2:

Input: x = -123
Output: -321

Example 3:

Input: x = 120
Output: 21

Constraints:

  • -231 <= x <= 231

如果用python的话,int不存在越界问题,因此最终判定是否超过了 -231 <= x <= 231

class Solution:
    def reverse(self, x: int) -> int:
        result = 0
        flag = 1
        if x < 0:
            flag = -1
            x = -x
        while x > 0:
            last = x % 10
            result = result * 10 + last
            x = x // 10
        return 0 if result > pow(2, 31) else result * flag

如果用java的话,int会越界,那么我们可以根据 (result * 10 + digit) / 10 == result , 来判定是否越界,因为如果越界的话除回去是不相等的

class Solution {
    public int reverse(int x) {
        int result = 0;
        while(x!=0){
            int digit = x % 10;
            //判定是否越界
            if((result * 10 + digit) / 10 != result) return 0;
            //没越界就继续加
            result = result * 10 + digit;
            x /= 10;
        }
        return result;
    }
}