1,问题
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: [−2^31, 2^31 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
2,想法:
(这部分与解题无关)首先对于32位的signed int值,取值范围是-2^32~2^32-1,这个是怎么来的呢?之前在学习数电和组原的时候都学习过相关的知识,现在再来复习一下,因为计算机中是采用补码的方式存储的,对于signed int,最高位是符号位,有效的数值位是31位。对于正数,补码与原码一致,对于负数,补码是除符号位外取反加1。因此,最大值0111 ...... 1111, 也就是2^32-1,最小值为1000 .... 0000, 求原码符号位不变,然后1111....1111+1为1000...0000,也就是-2^23。所以32位signed int值范围是 -2^32~2^32-1。
利用栈的思想,使得头变尾,尾变头,但是要注意符号的影响。一旦有溢出的情况,要返回0.
3,代码
class Solution {
public int reverse(int x) {
int max = Integer.MAX_VALUE;
int min = Integer.MIN_VALUE;
long verse = 0;
int remainder = 0;
int sign = 0;
if(x<0){
x = -x;
sign = 1;
}
while(x > 0){
remainder = x % 10;
verse = verse * 10 + remainder;
x = x / 10;
}
if(verse > max || verse < min)
return 0;
return sign==1?-(int)verse:(int)verse;
}
}
4,运行效率