LeetCode——Reverse Integer

Given a 32-bit signed integer, reverse digits of an integer.

  • Example 1:
    Input: 123
    Output: 321
  • Example 2:
    Input: -123
    Output: -321
  • Example 3:
    Input: 120
    Output: 21
Note:

Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

解法一

每个循环开始前判断res的值是否大于最大值/10,大于则直接返回0。

 public int reverse(int x) {
		int res=0;
		while(x!=0)
		{
			if(Math.abs(res)>Integer.MAX_VALUE/10)
				return 0;
			res=res*10+x%10;
			x=x/10;
		}
		return res;
	}

Runtime: 13 ms, faster than 100.00% of Java online submissions for Reverse Integer.
Memory Usage: 37.9 MB, less than 59.07% of Java online submissions for Reverse Integer.

解法二

如果数值溢出了的话,那么它除以10的值和未乘10之前的值是不相等的。

public int reverse(int x) {
	int res=0;
	while(x!=0)
	{
		int tmp=res*10+x%10;
		if(tmp/10!=res)
			return 0;
		res=tmp;
		x=x/10;
	}
	return res;
}

Runtime: 14 ms, faster than 99.97% of Java online submissions for Reverse Integer.
Memory Usage: 38 MB, less than 15.74% of Java online submissions for Reverse Integer.

  • 不能想得太复杂,此题的重点不是如何翻转,而是如何判断是否溢出。
  • 需要注意的是为何不用判断翻转后的值是否等于214748364,因为若res=214748364,翻转前的数字也要符合范围,则只能是1463847412,而它翻转过来之后是没有溢出的。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值