关闭

LeetCode:Reverse Integer

标签: LeetCodeReverse Integer
308人阅读 评论(0) 收藏 举报
分类:

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;
    }
};


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:324993次
    • 积分:6134
    • 等级:
    • 排名:第4062名
    • 原创:310篇
    • 转载:1篇
    • 译文:0篇
    • 评论:22条
    博客专栏
    最新评论