LeetCode 7 Reverse Integer(C,C++,Java,Python)

Problem:

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?

For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.


Solution:

To check for overflow/underflow, we could check if ret > 214748364 or ret < –214748364 before multiplying by 10. On the other hand, we do not need to check if ret == 214748364, why?

Average Rating: 3.5 (360 votes)

题目大意:

给一个整数,要求将整数逆序得到另外一个整数,如果逆序后的整数越界,返回0,

解题思路:

直接用res=res*10+x/10;x/=10;来解决,注意判断越界,越界判断方法为转化为double类型然后判断结果是否超出INT_MAX(2147483647)

Java源代码(用时228ms):

public class Solution {
    public int reverse(int x) {
        int flag=x>0?1:-1,res=0;
        x=x>0?x:-x;
        while(x>0){
            if(res*10.0 + x%10 > 2147483647)return 0;
            res = res*10+x%10;
            x/=10;
        }
        return res*flag;
    }
}


C语言源代码(用时10ms):

int reverse(int x) {
    int flag=x>0?1:-1,res=0;
    x=x>0?x:-x;
    while(x>0){
        if((2147483647.0-x%10)/10<res)return 0;
        res=res*10+x%10;
        x=x/10;
    }
    return res*flag;
}


C++源代码(用时13ms):

class Solution {
public:
    int reverse(int x) {
        int flag=x>0?1:-1,res=0;
        x=x>0?x:-x;
        while(x>0){
            if(res*10.0+x%10 > 2147483647)return 0;
            res = res*10+x%10;
            x/=10;
        }
        return res*flag;
    }
};


Python源代码(用时72ms):

class Solution:
    # @param {integer} x
    # @return {integer}
    def reverse(self, x):
        flag=1 if x>0 else -1
        x=x if x>0 else -x
        res=0
        while x>0:
            if res*10.0 + x%10 > 2147483647:return 0
            res = res*10+x%10
            x/=10
        return res*flag


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值