leetcode第7题——*Reverse Integer

25 篇文章 0 订阅
25 篇文章 0 订阅

题目

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.

思路

先将各位上的数字分别取出依次存放在一个数组里(个位、十位、百位、千位...),然后倒序取出数组即可(...、千位、百位、十位、个位),将结果存在res变量中,for循环得到res变量的值:res += a[i]*10^x。这里要注意的是翻转后溢出的情况——如果用Python编写,由于Python里不用声明变量类型,就算结果大于0x7fffffff也会自动转为长整型,因此直接用|res|>0x7fffffff表示溢出的情况;如果用Java编写,事先声明了int型变量,结果 大于 0x7fffffff则只会截取低32位的数,因此可以用最高位来判断是否溢出,详细设计见代码部分。

代码

Python
class Solution(object):
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        x_abs = abs(x)
        if (x_abs == 2147483648):
            return 0
        if (x_abs < 10):
            return x
        base = 1
        res,i = 0,0
        arr = []
        while (x_abs/(base*10) > 0) & (i < 10):
            base = pow(10,i)
            arr.append((x_abs/base)%10)
            i += 1
        i -= 1
        for j in range(i,-1,-1):
            if (arr[j] != 0):
                base = pow(10,abs(j-i))
                res += arr[j]*base#例如三位数123,原来的个位变百位,百位变个位
                if (res < 2147483648):
                    continue
                else:
                    return 0#溢出处理
        if (x < 0):
            return -res
        else:
            return res
Java
public class Solution {
    public int reverse(int x) {
        int x_abs = Math.abs(x);
		//特殊情况的处理
		if(x == -2147483648) return 0;
		if (x_abs < 10) return x;
		
		int[] arr = new int[11];
		int base = 1;
		int i,j;
		int res = 0;
	
		for(i = 0;x_abs/(base*10) > 0 && i < 10;i++){
			//将个位、十位、百位的数依次存在数组里
			base = (int)Math.pow(10, i);
			arr[i] = (x_abs/base)%10;
		}

		i -= 1;
		for(j = i;j >= 0;j--){
			if(arr[j] != 0){
					//例如三位数123,原来的个位变百位,百位变个位
					base = (int)Math.pow(10, Math.abs(j - i));
					res += arr[j]*base;
					//如果相加后的最高位是a[j]继续下次循环,否则代表溢出
					if(res/base == arr[j]) continue;
					else return 0;
			}
		}
		if(x < 0)
			return -res;
		else
			return res;
    }
}



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值