Gal.
Given a non-negative integer represented by a non-empty array of integers, add one to the number.
The highest digit is stored at the top of the array, where each element stores a single digit.
You can assume that the integer does not begin with zero, except for the integer 0.
See the LeetCode website for an example.
Source: LeetCode Link: https://leetcode-cn.com/probl… Copyright belongs to collar network. Commercial reprint please contact the official authorization, non-commercial reprint please indicate the source.
Solution 1: iterate through the array
Initializes the carry value adDone to 1, starting with the last digit of the array:
- Add the value of the current position to addOne;
- If the sum is 10, 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 value of the current value is set to the sum;
- Until the end of the traversal.
At the end of the traversal, if AdDone is 0, it returns the digits directly; If AdDone is 1, put 1 in the first place of the digits, and then 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 { return digits; } } public static void main(String[] args) { int[] digits = new int[]{4, 3, 2, 1}; Arrays.stream(plusOne(digits)).forEach(digit -> { System.out.print(digit + " "); }); }}
【 Daily Message 】
To wake in the morning with a leaping heart and give thanks for another day of loving.