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
思路
本题是个简单题
巧妙之处在于
long res = 0;
while(x!=0){
res = res*10 +x%10;
x =x/10;
}
每次%10得到最后一位 然后再res×10进一位
然后把原数x除10
class Solution {
public int reverse(int x) {
long res = 0;
while(x!=0){
res = res*10 +x%10;
x =x/10;
}
if(res >Integer.MAX_VALUE|| res<Integer.MIN_VALUE){
return 0;
}
return (int)res;
}
}