topic:
Given a 32-bit signed integer x, return the result of inverting the numeric portion of x. Returns 0
if the inverted integer exceeds the range [−2 31 , 2 31 − 1] of a 32-bit signed integer.
Assume the environment does not allow storing 64-bit integers (signed or unsigned).
Example 1:
Input: x = -123
Output: -321
solution:
class Solution {
public int reverse(int x) {
// 注意int类型反转后的数值可能超出int的表示范围,所以结果用long来存
long result = 0;
while(x != 0){
// 利用取模运算和除法运算进行整数反转
result = result * 10 + x % 10;
x = x / 10;
}
return (int)result == result ? (int)result : 0;
}
}