Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
示例 1:输入: 123 输出: 321
示例 2:输入: -123 输出: -321
public class Solution {
public static int reverse(int x) {
long ans = 0;
while (x != 0) {
ans = x % 10 + ans * 10;
x /= 10;
}
if (ans > Integer.MAX_VALUE || ans < Integer.MIN_VALUE)
return 0;
return (int) ans;
}
}
测试代码:
public class Test {
public static void main(String[] args) {
System.out.println(Solution.reverse(199318));
}
}
运行结果:813991