[LeetCode] Reverse Integer 解题报告

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?
Throw an exception? Good, but what if throwing an exception is not an option? You would then have to re-design the function (ie, add an extra parameter).

» Solve this problem

[解题思路]
如果是用字符串来逆序的话,需要考虑0的特殊性,但是如果直接用一个integer来滚动生成的话,0就不是问题了。
当然,溢出的问题是存在的,所以return -1。

[Code]

1:    int reverse(int x) {  
2: // Start typing your C/C++ solution below
3: // DO NOT write int main() function
4: int lastDigit = 0;
5: int result = 0;
6: bool isNeg = x>0? false:true;
7: x = abs(x);
8: while(x>0)
9: {
10: lastDigit = x%10;
11: result = result*10 + lastDigit;
12: x = x/10;
13: }
14: if(result<0) return -1;
15: if(isNeg)
16: result *=-1;
17: return result;
18: }

Version 2, Refactor code, 3/5/2012
Rethink for a while. And actually, we don’t need to use special logic to handle ‘+’ and ‘-‘, because the sign can be kept during calculating. Only 8 lines can resolve this problem.

1:       int reverse(int x) {  
2: int newN =0, left =0;
3: while(x != 0)
4: {
5: left = x%10;
6: newN = newN*10 + left;
7: x = x/10;
8: }
9: return newN;
10: }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值