[LeetCode]Reverse Integer

来源:互联网 发布:爱福窝效果图制作软件 编辑:程序博客网 时间:2024/05/16 18:59
思路:
1,考虑到 10, 100 的reverse都是1,这个情况就是一般情况的处理即可
2,溢出:只需要考虑 ret > 214748364 or ret < –214748364,如果ret == -214748364
因为,原始integer一定没有溢出,那么如果长度达到了最大长度,其最高位只能是 1或者2;
反过来把1或者2放在最后一位,也不会溢出,所以不用考虑 ret == -214748364这个情况 
public class Solution {    private static final int maxDiv10 = Integer.MAX_VALUE / 10;    private static final int minDiv10 = Integer.MIN_VALUE / 10;    public int reverse(int x) {        int num = 0;        while(x != 0){            int tmp = x % 10;            if ( num > maxDiv10 || num < minDiv10){                return 0;            }            num = num*10 + tmp;            x /= 10;        }        return num;    }}




———————————第一遍---------- 


解题思路:
1,如果只是reverse,问题就很简单。
2,要考虑到 负数,溢出等问题该怎么处理。

To check for overflow/underflow, we could check if ret > 214748364 or ret < –214748364 before multiplying by 10. On the other hand, we do not need to check if ret == 214748364, why?


class Solution {public:    int reverse(int x) {        bool minus = (x < 0 ? true : false);        x = abs(x);        int ret = 0;        int base = 0;        while (x != 0){            base = x % 10;            x = x / 10;            if (multiplication_is_safe(ret, 10)){                ret *= 10;            }else{                return 0;            }            if (addition_is_safe(ret, base)){                ret += base;            }else{                return 0;            }        }        return minus ? -ret : ret;    }    bool multiplication_is_safe(int32_t a, int32_t b){        int32_t p = a * b;        return !a || p/a == b;    }    bool addition_is_safe(int32_t a, int32_t b){        return (a + b >= 0);    }};


0 0
原创粉丝点击