LeetCode 7. Reverse Integer

197 阅读1分钟

7. Reverse Integer

Question

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: [−2^31^, 2^31^ − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

Solution

  • 从思路上来说,reverse这个任务可以利用栈先入后出的性质来实现,不过如果真的使用栈数据结构来实现的话需要先将int各位分离,再入栈出栈,再将各位数字转换为int。故可以只是用栈的思想。
  • x%10获得当前个位上的数字(带符号),x/10将位于右侧的各位数字逐一弹出,从右到左完成各位数字的遍历。(push
  • 原来的x从右到左的各位数字需要以从左到右的顺序组装成结果result。result = result * 10 + digit是将已有的数字进位,为后来数字留下空间。(pop
  • 需要考虑的是reverse之后的数字可能溢出,需要加入if检测。
    • 32-bit Int的INT_MAX, INT_MIN分别为2147483647和-2147483648,由于整数以二进制补码形式存储,故上下限制不对称。
class Solution {
public:
    int reverse(int x) {
        int result = 0;
        while(x != 0 ) {
            int digit = x%10;
            x = x/10;

            if (result>INT_MAX/10||(result==INT_MAX/10 && digit>7)) return 0;
            if (result<INT_MIN/10||(result==INT_MIN/10 && digit<-8)) return 0;
            result = result * 10 + digit;
        }
        return result;
    }
};