*LeetCode-Reverse Integer

来源:互联网 发布:数据库三范式概念 编辑:程序博客网 时间:2024/05/19 14:54

错惨了!!

1. 进制转换还是要练习!每次记得先做%余数,再做除法。

2.Math.floor 将double并没有转化成int 还要转化

3.这个题有复负数的情况,记得考虑!

4.整数溢出问题!!Integer.MAX_VALUE 2^31 -1

min value: -2^31

判断是否溢出的时候 要用计算结果判断 比如a+b < Integer.MAX_VALUE

 但是一旦赋值 c = a+b; c<Integer.MAX_VALUE 就已经溢出了 无法判断;????!!!what

并且一开始就要判断那个负数是否已经到达最小,否则一取绝对值就溢出了


public class Solution {    public int reverse(int x) {        boolean neg = false;        if ( x < 0){            if ( x == Integer.MIN_VALUE)                return 0;            x = Math.abs(x);            neg = true;        }                int ans = x / 10;        int rem = x % 10;        int step = 0;        int res = 0;        while ( ans != 0 ){            int length = (int)Math.floor(Math.log10(ans)) + 1;            if ( ( res + rem * Math.pow(10,length)) > Integer.MAX_VALUE)                return 0;            res += rem * Math.pow(10, length);            rem = ans % 10;            ans = ans /10;        }                if ( (res + rem) > Integer.MAX_VALUE)            return 0;        res += rem;        if (neg)            res = 0-res;        return res;            }}

别人的代码 觉得自己有点蠢

public class Solution {    public int reverse(int x) {        long result =0;        while(x != 0)        {            result = (result*10) + (x%10);            if(result > Integer.MAX_VALUE) return 0;            if(result < Integer.MIN_VALUE) return 0;            x = x/10;        }        return (int)result;    }}

他为什么可以先赋值再判断呢??!

看第二遍终于发现了 因为他用了long!!


0 0
原创粉丝点击