66. Plus One

    xiaoxiao2021-03-25  177

    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.

    问题:非负整型数被数组表示,比如{3,5,6,8,9}表示大数35689,给这个数+1,就是35690,输出新数组

    思想:大数加法。注意有进位发生比如9+1本位保存0,前一位要+1,还要考虑最高位是否会再进一位比如9999+1=10000

    public int[] plusOne(int[] digits) { int last=digits.length-1; int carry=(digits[last]+1)/10; digits[last]=(digits[last]+1); for(int i=last-1;i>=0;i--){ int n=digits[i]+carry; carry=n/10;//是否有进位 digits[i]=n; } if(carry==1){ int[] output=new int[digits.length+1]; output[0]=1; System.arraycopy(digits, 0, output, 1, digits.length); // for(int i=0;i<digits.length;i++){ // output[i+1]=digits[i]; // } return output; } else return digits; }

    转载请注明原文地址: https://ju.6miu.com/read-19315.html

    最新回复(0)