美文网首页
Leetcode66-数组模拟整数加1

Leetcode66-数组模拟整数加1

作者: 西5d | 来源:发表于2018-06-15 16:37 被阅读27次

    Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.
    You may assume the integer do not contain any leading zero, except the number 0 itself.
    The digits are stored such that the most significant digit is at the head of the list.
    As:
    [1,0,1] => [1,0,2]
    [9] => [1,0]
    [9,9] => [1,0,0]

    题目是模拟整数加一,重点就是在考虑进位,自己的解法稍显繁琐,首先考虑特殊情况,数组为空的异常处理;因为 数组保存是从低位到高位,实际整数的低位对应在数组索引的高位,首先给length-1的位置加1,(即实际的个位),默认进位数up=0,然后依次从数组高位length-1遍历,添加进位数,up=digits[i]/10digits[i] %= 10;最后,检查进位,如果进位up>0,对应整数最高位有进位,则将数组拷贝到新的lenght+1的数组中,完成。
    代码中同时提供了其他的简洁解法,供参考:

    public class Leet66 {
        public static void main(String[] args) {
    
            int[] arr = {1, 8, 9, 9};
            System.out.println(Arrays.toString(plusOne(arr)));
    
        }
    
        //other algorithm
        public static int[] plusOne2(int[] digits) {
            for (int i = digits.length - 1; i >= 0; i--) {
                if (digits[i] != 9) {
                    digits[i] = digits[i] + 1;
                    return digits;
                }
                digits[i] = 0;
            }
            int[] res = new int[digits.length + 1];
            res[0] = 1;
            return res;
        }
    
        //my algorithm
        public static int[] plusOne(int[] digits) {
            if (null == digits || digits.length == 0) {
                return new int[]{1};
            }
    
            int length = digits.length;
            digits[length - 1]++;
            int up = 0;
    
            for (int i = length - 1; i >= 0; i--) {
                digits[i] += up;
                up = digits[i] / 10;
                digits[i] %= 10;
            }
    
            if (up > 0) {
                int[] arr = new int[length + 1];
                System.arraycopy(digits, 0, arr, 1, length);
                arr[0] = 1;
                return arr;
            } else {
                return digits;
            }
    
        }
    }
    

    相关文章

      网友评论

          本文标题:Leetcode66-数组模拟整数加1

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