LeetCode Problems Solutions
question description: 问题描述
Reverse digits of an integer.
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.
将一个整数反向。
输入假定为一个32位的带符号整数。当反向的整数溢出时,函数应该返回0
Example:例如
Example1: x = 123, return 321
Example2: x = -123, return -321
Thinking
看到题目后最直接的思路可能是利用数组进行反向,然后将字符串转为int,最后判断溢出的问题。
还有另一种方法:
solution with java - Java解决方案
public static int reverse(int x) {
long tmp = x;
long ret = 0;
while (tmp != 0)
{
ret = ret * 10 + tmp % 10;
tmp /= 10;
}
if (ret > Integer.MAX_VALUE || ret < Integer.MIN_VALUE) {
return 0;
}
return (int)ret;
}
solution with swift - swift解决方案
func reverse(_ x: Int) -> Int {
var tmp = x
var ret = 0
while (tmp != 0)
{
ret = ret * 10 + tmp % 10;
tmp /= 10;
}
if ret > Int(Int32.max) || ret < Int(Int32.min) {
return 0;
}
return ret;
}