【Leetcode】7.Reverse Integer 解题

来源:互联网 发布:大数据与股票预测 编辑:程序博客网 时间:2024/06/05 04:26

【题目描述】:
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.


【思路分析】:
先获取绝对值以及设置负号标志位。
再对结果和数据进行每一位的处理,处理一次就判断一次溢出情况。


【我的代码】:

class Solution {public:    int reverse(int x) {        int result = 0;        int flag = x >= 0 ? 0 : 1;//为1,则在返回时加负号        int abValue = x > 0 ? x : -x;        while (abValue / 10 != 0 || (abValue / 10 == 0 && abValue % 10 != 0)) {            //检测溢出,不能写成result * 10 + abValue % 10 > INT_MAX,否则溢出已被截断            if (result > (INT_MAX-abValue % 10) / 10) {                return 0;            }            result = result * 10 + abValue % 10;            abValue /= 10;        }        return flag == 1 ? -result : result;    }};
0 0
原创粉丝点击