这个世界,它还是它。

只是,你的想法在变。

7. Reverse Integer

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

阅读更多
版权声明:欢迎批评指正。 https://blog.csdn.net/baibaibai66/article/details/52356056
文章标签: leetcode overflow
个人分类: Leetcode
上一篇35. Search Insert Position
下一篇二叉查找树BST(1)
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭