0007. 整数反转 #176
0007. 整数反转
#176
Replies: 2 comments
-
Java代码class Solution {
public int reverse(int x) {
int res = 0; // 初始化结果为 0,用于存储反转后的数字
while (x != 0) { // 当 x 不等于 0 时,继续循环
int tmp = res * 10 + x % 10; // 取 x 的最后一位数字,并加到结果的末尾
// 检查是否发生溢出
if (tmp / 10 != res) { // 如果 res 乘以 10 后与 tmp / 10 不相等,说明发生了溢出
return 0; // 返回 0 表示溢出
}
res = tmp; // 更新结果为反转后的数字
x /= 10; // 去掉 x 的最后一位数字
}
return res; // 返回最终反转的结果
}
} |
Beta Was this translation helpful? Give feedback.
0 replies
-
|
来自 @Felomeng 我的解法更好记一些 def reverse(self, x: int) -> int:
sign = [1, -1][x < 0]
ans, x = 0, abs(x)
while x:
x, c = divmod(x, 10)
ans = ans * 10 + c
if ans > 2**31 - 1:
return 0
return ans * sign |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
0007. 整数反转
https://algo.itcharge.cn/solutions/0001-0099/reverse-integer/
Beta Was this translation helpful? Give feedback.
All reactions