LeetCode——Reverse Integer(逆置一个整数)

时间:2022-11-15 21:30:24
问题:

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return –321

 

Have you thought about this?

Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!

If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.

 

Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?

Throw an exception? Good, but what if throwing an exception is not an option? You would then have to re-design the function (ie, add an extra parameter).

分析:

简单的分析逆置一个整数比较简单,代码如下:

public class Solution {
public int reverse(int x) {
int result = 0;
while(x != 0){
result = result*10+x%10;
x = x/10;
}
return result;
}
}

上面的代码对于类似10100这样的数逆置之后就变为了101,也算可以接受,但是没有考虑溢出的问题。

 

在考虑溢出这个问题上,

我们可以先把原数x的符号位记录下来,在java中x的符号位可以获取为 int sign=x>>31,当sign为-1表示为负数,否则为正。

然后按照上面的方法求逆置的数result,再判断result的符号位是否和原数x相同,若相同则没有溢出;否则溢出。

实现的代码如下:

public int  reverse2(int x) {
int result = 0;
int sign = x>>31;
while (x != 0) {
result = result * 10 + x % 10;
x = x / 10;
}
// System.out.println(sign+", "+(result>>31));
if(sign!=(result>>31)){
System.out.println("overflow..");
System.exit(1);
}
return result;
}

 


以下是我用于测试的完整代码:

public class ReverseInt {
public static void main(String[] args) {
ReverseInt r = new ReverseInt();
System.out.println(r.reverse2(123));
System.out.println(r.reverse2(1230));
System.out.println(r.reverse2(-123));
System.out.println(r.reverse2(1000000003)); }
public int reverse(int x) {
int result = 0;
while (x != 0) {
result = result * 10 + x % 10;
x = x / 10;
}
return result;
}
public int reverse2(int x) {
int result = 0;
int sign = x>>31;
while (x != 0) {
result = result * 10 + x % 10;
x = x / 10;
}
// System.out.println(sign+", "+(result>>31));
if(sign!=(result>>31)){
System.out.println("overflow..");
System.exit(1);
}
return result;
}
}