7. Reverse Integer LeetCode题解

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: 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.

注意:

输入是32位有符号整数,当翻转整数越界的时候,你的函数应该返回0

Subscribe to see which companies asked this question.


题解:

本题关键在于越界的判断,有两种思路:

1. 使用更多位数的类型,比如long;

(全部转换为long之后不会存在越界问题,只是在输出时需要做一判断,即是否超越原int范围)

2. 使用以除代乘,以减代加的方式检验是否越界;

(比如int最大值为INT_MAX,当前值为num1,判断num1+num2是否越界的方式为,判断INT_MAX-num2是否小于num1)


Code 【Java/C++】

public class Solution {
    public int reverse(int x) {
        int ans = 0;
        for (int tail = 0; x != 0; x /= 10) {
            tail = x % 10;
            int tmp = ans * 10 + tail;
            if ((tmp - tail) / 10 != ans) {
                return 0;
            }
            ans = tmp;
        }
        return ans;
    }
}


猜你喜欢

转载自blog.csdn.net/baidu_23318869/article/details/71600549