LeetCode--Reverse Integer

来源:互联网 发布:如何优化你的页面 编辑:程序博客网 时间:2024/04/30 21:54

Problem:

Reverse digits of an integer.

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

click to show spoilers.

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?

For the purpose of this problem, assume that your function returns 0
when the reversed integer overflows.

Analysis:
Reverse digits of an integer.

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

注意: 一些边界条件的考虑可以在笔试或面试时为你的代码带来加分的效果

 1. int x =0的情况,单独处理。 1.考虑翻转后的溢出问题;     一般溢出情况需要出题人声明 异常处理。 2. 如果最后都是0,该怎么处理?  例如 10,100等?  所以while判断的终止条件应该是x!=0  而不是余数怎么着怎么着。

这道题思路非常简单,就是按照数字位反转过来就可以,基本数字操作。但是这种题的考察重点并不在于问题本身,越是简单的题目越要注意细节,一般来说整数的处理问题要注意的有两点,一点是符号,另一点是整数越界问题。
Anwser1:

public class Solution {public static int reverse(int x) {        Queue<Integer> nums = new LinkedList<>();        int i=0;        int res=0;        boolean flag=false;        if (x<0) {            flag=true;            x = -x;        }        while(x>0){            nums.add(x % 10);            x = x / 10;        }        while(nums.peek()!=null){            res = res * 10 + nums.poll();         }        if (flag) return -res;        else return res;    }}

这个方法没有过,报错知识failed,而我自己在控制台测试没有问题,不知道到底什么原因,如果有知道的可以评论告诉我,
不过这个方法是在是太罗嗦了。
Anwser2:

public class Solution {    public int reverse(int x) {        int res=0;        boolean flag=false;        if (x<0) {            flag=true;            x = -x;        }        while(x>0){            res = res*10 + x%10;            x = x / 10;        }        if (flag) return -res;        else return res;    }}

但是结果为:
这里写图片描述

我很不理解,为什么会是这样,而且1534236469 < INT_MAX(2^31=2147483648),后来我才明白,因为1534236469结果应该为9645324351,这个数超过了INT_MAX,所以结果大于INT_MAX和小于-INT_MAX的应该返回0;

Anwser3:
int INT_MAX = 2147483647;

public class Solution {    public int reverse(int x) {        long res=0;        boolean flag=false;        if (x<0) {            flag=true;            x = -x;        }        while(x>0){            //  标记1            res = res*10 + x%10;            x = x / 10;        }        if(res>Integer.MAX_VALUE || res <Integer.MIN_VALUE) return 0;//  标记2        if (flag)  res=-res;        return (int)res;    }}

其实这个anwser3也是改了好多遍,可以有以下几点收获:

  • if(flag) return -res;else return res;看的语句复杂,不如改为:if(flag) res =-res; return res;
  • Integer.MAX_VALUE值为 2的31次方-1 的常量,它表示 int 类型能够表示的最大值,但是不能让int=2^31-1;报错整数过大。需要long res;
  • 最后返回时可以用(int)res;强行将long类型转为int类型。
  • 标记2处也可以没有,在标记1处做处理。if(res>(Integer.MAX_VALUE-x%10)/10) return 0;或者if(res*10/10!=res) return 0;
0 0