美文网首页
LeetCode每日一题:reverse integer

LeetCode每日一题:reverse integer

作者: yoshino | 来源:发表于2017-07-06 09:28 被阅读15次

    问题描述

    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?
    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).

    问题分析

    翻转int,主要考点在于怎么处理正负和溢出。

    代码实现

    public int reverse(int x) {
            if (x == 0) return 0;
            String num = String.valueOf(x);
            int inx = 0;
            boolean minus = false;
            if (num.charAt(0) == '-') {
                minus = true;
                inx++;
            }
            long result = 0;
            int flag = 1;
            if (minus) flag = -1;
            for (int i = num.length() - 1; i >= inx; i--) {
                result = result * 10 + flag * (num.charAt(i) - '0');
                if (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE) return 0;
            }
            return (int) result;
        }
    

    相关文章

      网友评论

          本文标题:LeetCode每日一题:reverse integer

          本文链接:https://www.haomeiwen.com/subject/wnachxtx.html