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.
翻转字符串,简单但是有陷阱,需要判断翻转后是否超过了int范围,范围在[-2147483648,2147483647],需要中间判断一下,乘以10后是否越界
static class Solution {
public int reverse(int x) {
if (x == 0) return x;
boolean mines = false;
if (x < 0){
mines = true;
x = Math.abs(x);
}
int ans = 0;
while (x > 0)
{
if (ans > Integer.MAX_VALUE / 10) return 0;
ans = ans * 10 + x % 10;
x = x / 10;
}
if (mines)
ans = -ans;
return ans;
}
}
本文介绍了一个算法挑战:在32位有符号整数范围内翻转整数的每一位。通过实例展示了输入123返回321,输入-123返回-321的过程。特别注意,算法需判断翻转后的整数是否超出范围[-2^31, 2^31-1],并在溢出时返回0。
1516

被折叠的 条评论
为什么被折叠?



