关闭

7. Reverse Integer

标签: leetcodeoverflow
66人阅读 评论(0) 收藏 举报
分类:

Title

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.

Solution

class Solution {
public:
    int reverse(int x) {
        int y = 0;

        while (x != 0) {
            int yy = y*10 + x%10;

            if (yy%10 != x%10) { //判断整数溢出
                return 0;
            }
            else {
                y = yy;
            }

            x /= 10;
        }

        return y;
    }
};

整数溢出那里挺巧妙的,如果逆置过程中当前数字和原来的数字不同,则出现了溢出,返回0.

runtime: 8ms

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:24640次
    • 积分:1169
    • 等级:
    • 排名:千里之外
    • 原创:97篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条