plus-one

/**
* Given a number represented as an array of digits, plus one to the number.
*
* 给定一个以数字数组表示的数字,再加上一个数字。
*/

/**
 * Given a number represented as an array of digits, plus one to the number.
 *
 * 给定一个以数字数组表示的数字,再加上一个数字。
 */

public class Main49 {
    public static void main(String[] args) {
        int[] digits = {0,1,7,6,9,9,9,9,9,9};
        int[] plusOne = Main49.plusOne(digits);
        for (int i=0; i<plusOne.length; i++) {
            System.out.print(plusOne[i] + " ");
        }
    }

    public static int[] plusOne(int[] digits) {
        for(int i=digits.length-1;i>=0;i--) {
            if(digits[i]!=9) {
                digits[i]+=1;
                break;
            }else {
                digits[i] = 0;
            }
        }
        if(digits[0]==0) {
            int temp[] = new int[digits.length+1];
            temp[0] = 1;
            for(int j=1;j<temp.length;j++) {
                temp[j] = 0;
            }
            return temp;
        }
        return digits;
    }
}

  

原文地址:https://www.cnblogs.com/strive-19970713/p/11344746.html