# LeetCode:Reverse Integer

440人阅读 评论(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.

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):

Subscribe to see which companies asked this question

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

个人资料
等级：
访问量： 39万+
积分： 6850
排名： 4142
博客专栏
 Java源码解析 文章：12篇 阅读：13297 LeetCode解题记录 文章：216篇 阅读：277540 FFmpeg4Android 文章：7篇 阅读：1014
最新评论
友情链接