【LeetCode练习】[简单]7. 整数反转
7. 整数反转
题目来源 算法思想:编程中 % / 的利用
题目:利用long来判断溢出情况 注意:溢出的情况,分为正数的溢出以及负数的溢出;
java代码
class Solution {
public int reverse(int x
) {
int tmp
= 0;
Long res
= 0L
;
while(x
!= 0) {
tmp
= x
% 10;
if (res
* 10 > Integer
.MAX_VALUE
|| res
* 10 + tmp
> Integer
.MAX_VALUE
|| res
* 10 < Integer
.MIN_VALUE
|| res
* 10 + tmp
< Integer
.MIN_VALUE
){
return 0;
}
res
= res
* 10 + tmp
;
x
= x
/ 10;
}
return res
.intValue();
}
}
java代码–存放结果不用long
class Solution {
public int reverse(int x
) {
int tmp
= 0;
int res
= 0;
while(x
!= 0) {
tmp
= x
% 10;
int newRes
= res
* 10 + tmp
;
if (newRes
/ 10 != res
){
return 0;
}
res
= newRes
;
x
= x
/ 10;
}
return res
;
}
}
转载请注明原文地址: https://lol.8miu.com/read-36474.html