[LeetCode]Reverse Integer

LeetCode的题目一般都很简短,经常要自己想各种可能的测试样例。


题目:

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

这题坑爹的地方在于1000000003-2^31这样的数翻转之后会溢出(返回0)。

我用的是比较low的方法,就是用long long:

int reverse(int x) {
		long long n;
		vector<int> digits;
		long long result = 0;
		long long power = 1;

		n = x >= 0 ? (long long)x : -(long long)x;  //  -2^31简直是个特例!

		while (n != 0) {
			digits.push_back(n%10);
			n /= 10;
		}

		for (int i = digits.size() - 1; i >= 0; i--) {
			result += digits[i] * power;
			power *= 10;
		}

		if (result > 2147483647)  //  2^31-1
			return 0;

		return x >= 0 ? (int)result : -(int)result;
}

官方提供的判定溢出的方法:

To deal with overflow, inspect the current number before multiplication. 


If the current number is greater than 214748364, we know it is going to overflow. 


On the other hand, if the current number is equal to 214748364, we know that it will overflow only when the current digit is greater than or equal to 8.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值