题目描述:Given a 32-bit signed integer, reverse digits of an integer.
note:Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
汉语理解:给出一个32位有符号整数的反转表示。
解题思路:将数字首先转换成正数,然后依次从低位获取原始数字正数的每一个数字,获取最低位时这个数字保存在一个变量中res,获取次低位时,将count*10+次低位赋值给count,再获取倒数第三位数字时,将count*10+倒数第三位数字赋值给count,一次类推,即可得到原始数绝对值的反转数字,再根据范围进行约束,防止数值溢出。
代码(java):
class Solution {
public int reverse(int x) {
int tag=0;
if(x<0){
tag=1;
x=0-x;
}
long res=0;
while(x>0){
int tail=x%10;
res=res*10+tail;
x=x/10;
}
if(tag==1)res=0-res;
if(res> Integer.MAX_VALUE || res<Integer.MIN_VALUE)res=0;
return (int) res;
}
}