[LeetCode-Algorithms-7] "Reverse Integer" (2017.9.14-WEEK2)

来源:互联网 发布:云盘服务器架设php 编辑:程序博客网 时间:2024/06/03 12:32

题目链接:Reverse Integer


  • 题目描述:

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.


(1)思路:因为做得上一题是判断回文数,用的逆序整数,所以把这个题放在9的后面来做,因为这个需要判断的多一点点。我把负数的符号在计算时去掉,然后在输出时再加上,这样和正数逆序计算就一样了。然后就是判断逆序以后是否会溢出。对于后面跟0的数字,没有什么影响,因为计算时0*10还是0,所以输出是正常的符合我们逻辑的逆序数字。

(2)代码:

int reverse(int x) {        int flag = 0;        int ans = 0;        if (x < 0) {            flag = 1;            x *= -1;         }        while (x > 0) {            if (ans > INT_MAX / 10) return 0;            ans = x % 10 + ans * 10;            x = x / 10;        }        if (flag) return -ans;        else return ans;}

(3)提交结果:

这里写图片描述