给你一个 32 位的有符号整数 x
,返回将 x
中的数字部分反转后的结果。
如果反转后整数超过 32 位的有符号整数的范围 [−231, 231 − 1]
,就返回 0。
假设环境不允许存储 64 位整数(有符号或无符号)。
示例 1:
输入:x = 123 输出:321
示例 2:
输入:x = -123 输出:-321
示例 3:
输入:x = 120 输出:21
示例 4:
输入:x = 0 输出:0
提示:
-231 <= x <= 231 - 1
C++
#include <climits>
#include <iostream>
using namespace std;
class Solution {
public:
int reverse(int x) {
int ans = 0;
for (; x; x /= 10) {
if (ans < INT_MIN / 10 || ans > INT_MAX / 10) {
return 0;
}
ans = ans * 10 + x % 10;
}
return ans;
}
};
void main()
{
Solution sol;
int data = 123;
int ret = sol.reverse(data);
cout << ret << endl;
}
c#
public class Solution
{
public int Reverse(int x)
{
int ans = 0;
for (; x != 0; x /= 10)
{
if (ans < int.MinValue / 10 || ans > int.MaxValue / 10)
{
return 0;
}
ans = ans * 10 + x % 10;
}
return ans;
}
public static void Main(string[] args)
{
Solution sol = new Solution();
int x = 123;
int ret = sol.Reverse(x);
Console.WriteLine(ret);
}
}
Python
from typing import ChainMap
class Solution:
def reverse(self, x: int) -> int:
ans = 0
mi, mx = -(2**31), 2**31 - 1
while x:
if ans < mi // 10 + 1 or ans > mx // 10:
return 0
y = x % 10
if x < 0 and y > 0:
y -= 10
ans = ans * 10 + y
x = (x - y) // 10
return ans
solution = Solution()
result = solution.reverse(123)
print(result)
Java
class Solution {
public int reverse(int x) {
int ans = 0;
for (; x != 0; x /= 10) {
if (ans < Integer.MIN_VALUE / 10 || ans > Integer.MAX_VALUE / 10) {
return 0;
}
ans = ans * 10 + x % 10;
}
return ans;
}
public static void main(String[] args) {
Solution sol = new Solution(); // 创建Solution类的实例
int x = 123;
int result = sol.reverse(x);
System.out.println(result); // 打印结果
}
}