Gal.

Given a non-negative integer represented by a non-empty array of integers, add one to that number.

The highest digit is stored at the beginning of an array, where each element stores only a single digit.

You can assume that this integer does not start with zero, except for the integer 0.

Examples can be found on the LeetCode website.

Source: LeetCode link: leetcode-cn.com/problems/pl… Copyright belongs to the Collar buckle network. Commercial reprint please contact official authorization, non-commercial reprint please indicate the source.

Solution 1: go through the number group

Initialize a carry value addOne to 1, traversing forward from the last digit of the array digits:

  • Add the value of the current position to addOne;
  • If the sum is 10, the carry is generated, addOne is set to 1, and the current value is set to 0;
  • If the sum is less than 10, no carry is generated, addOne is set to 0, and the current value is set to the sum;
  • Until the end of the iteration.

At the end of the walk, if addOne is 0, return digits directly; If addOne is 1, place 1 first of digits and return.

import java.util.Arrays;

public class LeetCode_066 {
    public static int[] plusOne(int[] digits) {
        int addOne = 1;
        for (int i = digits.length - 1; i >= 0; i--) {
            if (addOne + digits[i] == 10) {
                addOne = 1;
                digits[i] = 0;
            } else {
                digits[i] = addOne + digits[i];
                addOne = 0; }}if (addOne == 1) {
            int[] result = new int[digits.length + 1];
            result[0] = addOne;
            for (int i = 0; i < digits.length; i++) {
                result[i + 1] = digits[i];
            }
            return result;
        } else {
            returndigits; }}public static void main(String[] args) {
        int[] digits = new int[] {4.3.2.1};
        Arrays.stream(plusOne(digits)).forEach(digit -> {
            System.out.print(digit + ""); }); }}Copy the code

Wake up in the morning with a leaping heart and give thanks for another day of love.