题目:
7. 整数反转
题解:数学方法
注意:[−2^(31), 2^(31) − 1] == [−2147483648, 2147483647]
代码:数学方法
import java
.util
.Scanner
;
public class code7 {
public static int reverse(int x
) {
int rev
= 0;
while (x
!= 0) {
int pop
= x
% 10;
x
/= 10;
if (rev
> Integer
.MAX_VALUE
/ 10 || (rev
== Integer
.MAX_VALUE
/ 10 && pop
> 7)) {
return 0;
}
if (rev
< Integer
.MIN_VALUE
/ 10 || (rev
== Integer
.MIN_VALUE
/ 10 && pop
< -8)) {
return 0;
}
rev
= rev
* 10 + pop
;
}
return rev
;
}
public static void main(String
[] args
) {
Scanner sc
= new Scanner(System
.in
);
while (sc
.hasNextInt()) {
int x1
= sc
.nextInt();
int x2
= reverse(x1
);
System
.out
.println(x2
);
}
}
}
参考:
7. 整数反转——解析一【leetcode】Reverse Integer整数反转----Java代码实现INT_MAX和INT_MIN注意事项Integer的MIN_VALUE关于JAVA的Scanner(System.in)循环输入的一些问题与解决java怎么循环输入数字,然后按回车就知道跳出循环?