[LeetCode]007. 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).

Solution:

use the math method to reverse the order, 

result = result*10 + left;

the + operation in the while loop can eliminate the redundant 0; such as “500--->5 (which is '0+0+5')";

use the Math.abs() method to get the abstract value, because the module on negative number has ambiguity.(different languages have different results).


负数取模有争议,不同的编程语言给出的结果不同,参见

http://ceeji.net/blog/mod-in-real/

实数范围内的求模(求余)运算:负数求余究竟怎么求


java里表示整数最大值Integer.MAX_VALUE  (2^31 -1);


public class Solution {
    public int reverse(int x) {
        // Start typing your Java solution below
        // DO NOT write main() function
        int flag = 1;
        if(x<0){
            flag = -1;
        }
        int temp = Math.abs(x);
        int left = 0;
        int result = 0;
        while(temp != 0){
            left = temp % 10;
            result = result*10 + left;
            temp = temp/10;
        }
        if(result > Integer.MAX_VALUE){
            return -1;
            // only return -1 here, or we can print one message 
            //or use a static field variable "isValid" for representint states?
        }else{
            return result*flag;
        }
    }
}


2015-04-03 update:

python solution: 仍然使用数学求模,这样可以有效加速对于10000000这样的数据的处理。

1. leetcode对于overflow的处理的返回值由原先的-1改成了0,因此python解法中一并更改。

2. python中最大值可以由sys.maxint表示,但不同系统的返回值不同,这里统一使用2^31 - 1

Time Complexity: O(n)

#import sys
class Solution:
    # @return an integer
    def reverse(self, x):
        if x >= 0:
            flag = 1
        else:
            flag = -1
        temp = abs(x)
        result = 0
        while temp > 0:
            left = temp % 10
            temp /= 10
            result = result * 10 + left
        #if result > sys.maxint:
        if result > pow(2, 31) - 1:
            return 0
        else:
            return flag * result


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值