Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0.
给你一个 32 位的有符号整数 x ,返回将 x 中的数字部分反转后的结果。
如果反转后整数超过 32 位的有符号整数的范围 [−231, 231 − 1] ,就返回 0。
Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
假设环境不允许存储 64 位整数(有符号或无符号)。
Example 1:
Input: x = 123
Output: 321
示例 1:
输入:x = 123
输出:321
Example 2:
Input: x = -123
Output: -321
示例 2:
输入:x = -123
输出:-321
Example 3:
Input: x = 120
Output: 21
示例 3:
输入:x = 120
输出:21
示例 4:
输入:x = 0
输出:0
Constraints:提示:
-<= x <=
- 1
C语言:
int reverse(int x){
long int r=0;
while(x)
{
if(r>INT_MAX/10||r<INT_MIN/10)
{
return 0;
}
r=r*10+x%10;
x=x/10;
}
return r;
}
执行结果:通过
执行用时:4 ms, 在所有 C 提交中击败了56.33%的用户
内存消耗:5.4 MB, 在所有 C 提交中击败了71.08%的用户
通过测试用例:1032 / 1032