首页 > 其他分享 >[LeetCode]7. Reverse Integer (easy)

[LeetCode]7. Reverse Integer (easy)

时间:2023-01-18 10:36:01浏览次数:48  
标签:10 curr int res sign easy Integer LeetCode


​Welcome To My Blog​

7. Reverse Integer (easy)

[LeetCode]7. Reverse Integer (easy)_取值范围


1. 在java中,数值溢出后还能计算,只不过得到的计算结果不正确,可以设置两个变量并利用这一点进行溢出判断

[LeetCode]7. Reverse Integer (easy)_带符号_02


[LeetCode]7. Reverse Integer (easy)_带符号_03


2. 因为在res = res * 10 + curr;形式下,0没有贡献,所以不用专门处理leading 0

3. 可以保留符号运算,负数+负数或者正数+正数,带符号运算时要注意循环条件是 x != 0,而不是x > 0

3. 题目要求溢出时返回0,在处理上与溢出时返回Max或Min有所不同

4. 按照一般情况和边界情况讨论

+ 一般情况: -123

+ 边界情况: 120,100100,翻转后溢出

+ 最高位取值范围[1,9],个位取值范围[0,9]

+ 保留符号

+ 避免0开头

+ 避免溢出

原始版本,正负数,leading 0以及判断溢出都不够简洁

public static int reverse(int x) {
int res = 0, curr = 0, sign = 1;
//1. 提取符号
sign = sign * x < 0 ? -1 : 1;
//2. 转化为正数
x = x * sign;
while ( x > 0){
//3. 当前的数字
curr = x % 10;
//4.1 个位数前面有几个数就要乘几次10;
//4.2 十位数前面有几个数就要成几次10;同理...
x /= 10;
//5 avoid overflow
boolean overflow =(res > Integer.MAX_VALUE / 10) || res == Integer.MAX_VALUE / 10 && (curr > Integer.MAX_VALUE % 10 || curr*sign < Integer.MIN_VALUE % 10 ) ;
if (overflow) return 0;

res = res * 10 + curr;
}
return res * sign;
}

最优解

public static int reverse(int x) {
int res = 0;
// 带符号运算的话这里得是 x!=0
while (x != 0){
int curr = x % 10;
int tempRes = res * 10 + curr ;
// if overflow?
if((tempRes -curr) / 10 != res) return 0;
res = tempRes;
x /= 10;
}
return res;
}


标签:10,curr,int,res,sign,easy,Integer,LeetCode
From: https://blog.51cto.com/u_2420922/6019031

相关文章