问题描述
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
将一个有符号整数进行反转
解题思路
- 取绝对值
- 对绝对值 进行求余操作,同时 / 10
- 根据输入值的符号,进行符号变化
代码
代码语言:javascript复制class Solution {
public int reverse(int x) {
long result = 0;
long abs = (long)(Math.abs(x));
while (abs > 0) {
result = result * 10 abs % 10;
abs = abs / 10;
}
if (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE) {
result = 0;
}
result = x > 0 ? result : -result;
return (int)result;
}
}