66. Plus One

Given a non-empty array of digits representing a non-negative integer, plus one to the integer.

The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.

You may assume the integer does not contain any leading zero, except the number 0 itself.

Example 1:

Input: [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.

Example 2:

Input: [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.
使用高精度加法
class Solution {
    public int[] plusOne(int[] digits) {
        // int carry = 0;
        // int s = 1;
        // for(int i = digits.length-1;i>=0;i--){
        //     if(i==digits.length-1){
        //         s = 1;
        //     }
        //     else s=0;
        //     int cur = digits[i]+s+carry;
        //     if(cur==10){
        //         digits[i]=0;
        //         carry=1;
        //     }
        //     else{
        //         carry=0;
        //         digits[i]=cur;
        //     }
        // }
        // if(carry==1){
        //     int[] digit = new int[digits.length+1];
        //     digit[0]=1;
        //     System.arraycopy(digits,0,digit,1,digits.length);
        //         return digit;
        // }
        // else{
        //    return digits;
        // }
        int l = digits.length - 1;
        int s = 1;
        for(int i = l; i >= 0; i--){
            digits[i] += s;
            s = digits[i] / 10;
            digits[i] %= 10;
        }       
        if(s == 1){
            int[] digit = new int[l+2];
            digit[0] = 1;
            System.arraycopy(digits, 0, digit, 1, digits.length);
            return digit;
        } 
        else return digits; 
    }

从后往前,先给末位+1,然后看是否需要进位。结束后看最后是否需要进位,若需要,使用System.arraycopy(源数组,起始位置,目的数组,起始位置,长度)。如果不需要就直接返回modified的数组


posted @ 2019-08-07 03:57  Schwifty  阅读(141)  评论(0编辑  收藏  举报