7. Reverse Integer

来源:互联网 发布:淘宝开店卖食品 编辑:程序博客网 时间:2024/05/23 07:23

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

Have you thought about this?
Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!

If the integer’s last digit is 0, what should the output be? ie, cases such as 10, 100.

Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?

For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.

这道题把数字倒过来很简单,难点在于判断倒过来的数是否溢出。
第一种方法是使用long long类型来表示倒转后的数字,long long是64位,可以检测出int的溢出:

class Solution {public:    int reverse(int x) {        long long reversedNum = 0;        while (x != 0) {            reversedNum = reversedNum * 10 + x % 10;            x /= 10;        }        if (reversedNum < INT_MIN || reversedNum > INT_MAX) return 0;        return reversedNum;    }};

第二种方法:每次颠倒数字的时候,都记下上一次操作得到的数字(lastRevertedNum),如果出现了溢出,则总有一次操作会出现差错

class Solution {public:    int reverse(int x) {        int reversedNum = 0, lastReversedNum = 0;        while (x != 0) {            reversedNum = reversedNum * 10 + x % 10;            //判断是否出现差错            if ((reversedNum - x % 10) / 10 != lastReversedNum)                return 0;            x /= 10;            lastReversedNum = reversedNum;        }        return reversedNum;    }};
原创粉丝点击