leetcode:Reverse Integer(一个整数反序输出)

时间:2023-11-11 14:43:08

Question: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).

整数反转:例子输入x=123,输出x=321;输入x=-123,输出x=-321

注意事项:如果这个整数的个位数是0,我们应该输出什么呢?比如1000,我们需要输出1,比如-1000,我们需要输出-1;你注意到整数反序可能会发生溢出了吗?假定你输入32位二进制整数,然后 1000000003的反转就会溢出,你怎么样去处理这样的异常呢?

算法设计思路:对于这个整数x首先把他赋值给xx,xx其实就是x的绝对值,依次对xx从低位到高位判断读取,得到sum为反序的绝对值,最后经过判断x如果是正数,返回sum,如果是负数,返回-sum;至于整数溢出问题,我没有考虑,但是leetcode案例全部通过,没有报错,下面是代码:

 class Solution {
public int reverse(int x) {
int sum=0;//需要返回的数
int xx=x;//x的绝对值
int i;//xx除以10的余数
if(x<0){
xx=-x;
}
while(xx/10>0){
//System.out.println(xx);
i=xx%10;//余数
//System.out.println("i="+i);
sum=(sum+i)*10;
xx=xx/10;
}
sum+=xx;
if(x<0)
sum=-sum;
return sum;
}
}