LeetCode:Reverse Integer

Reverse Integer

Total Accepted: 108334 Total Submissions: 462300 Difficulty: Easy

Reverse digits of an integer.

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

click to show spoilers.

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.

Update (2014-11-10):
Test cases had been added to test the overflow behavior.

Subscribe to see which companies asked this question

Hide Tags
 Math
Hide Similar Problems
 (E) String to Integer (atoi)



































code:

class Solution {
public:
    int reverse(int x) {
        if(0 == x) return 0;
        int ret;
        long long sum = 0;
        while(0 == x % 10) x /= 10;
        while(x) {
            sum = sum * 10 + x % 10;
            x /= 10;
        }
        ret = sum;
        if(ret == sum) return ret;
        else return 0;
    }
};


阅读更多
版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/itismelzp/article/details/49950237
文章标签: LeetCode Reverse Integer
个人分类: LeetCode OJ
所属专栏: LeetCode解题记录
上一篇LeetCode:Path Sum
下一篇LeetCode:Minimum Depth of Binary Tree
想对作者说点什么? 我来说一句

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

关闭
关闭