Plus One 解答

Question

Given a non-negative number represented as an array of digits, plus one to the number.

The digits are stored such that the most significant digit is at the head of the list.

Solution

To solve this problem, we can use a flag to mark if the current digit needs to be changed.

Time complexity O(n), space cost O(n)

 1 public class Solution {
 2     public int[] plusOne(int[] digits) {
 3         int length = digits.length;
 4         int[] result = new int[length + 1];
 5         int flag = 1;
 6         for (int i = length - 1; i >= 0; i--) {
 7             if (flag == 1) {
 8                 if (digits[i] < 9) {
 9                     digits[i] += 1;
10                     flag = 0;
11                 } else {
12                     digits[i] = 0;
13                 }
14             }
15         }
16         if (flag == 1) {
17             for (int i = 0; i < length; i++)
18                 result[i + 1] = digits[i];
19             result[0] = 1;
20             return result;
21         }
22         return digits;
23     }
24 }
原文地址:https://www.cnblogs.com/ireneyanglan/p/4799830.html