题目
给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
示例 1:
输入: 123
输出: 321
示例 2:
输入: -123
输出: -321
示例 3:
输入: 120
输出: 21
注意:
假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−231, 231 − 1]。请根据这个假设,如果反转后整数溢出那么就返回 0。
题解
这道题的整体思路是先确定正负,然后用while loop 把末尾的零都消掉,输入除十取余数,输出*10+余数,难点在与边界溢出问题和次方问题,1<<31代表2的31次方,也可以用Math.power(x,y)来表示
class Solution {
public int reverse(int x) {
if(x == 0) return 0;
int positive = 1;
if(x < 0){
positive = 0;
x = -1 * x;
}
int res = 0;
int rest = 0;
while(x % 10 == 0){
x = x/10;
}
while(x > 0){
rest = x % 10;
x = x / 10;
if (Math.abs(res) > ((1 << 31) - 1) / 10) return 0;
res = res * 10 + rest;
}
if(positive == 0) res = -1 * res;
return res;
}
}