# [LeetCode/LintCode] Plus One

linspiration

## Problem

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.

## Example

Given [1,2,3] which represents 123, return [1,2,4].

Given [9,9,9] which represents 999, return [1,0,0,0].

## Update 2018-9

``````class Solution {
public int[] plusOne(int[] digits) {
int n = digits.length;
for (int i = n-1; i >= 0; i--) {
if (digits[i] == 9) {
digits[i] = 0;
} else {
digits[i]++;
return digits;
}
}
int[] res = new int[n+1];
res[0] = 1;
return res;
}
}``````

``````public class Solution {
public int[] plusOne(int[] digits) {
int carry = 1;
for (int i = digits.length-1; i >= 0; i--) {
int cur = digits[i] + carry;
carry = cur / 10;
digits[i] = cur % 10;
if (carry == 0) break;
}
if (carry == 1) {
int[] res = new int[digits.length+1];
res[0] = 1;
return res;
}
return digits;
}
}
``````

``````public class Solution {
public int[] plusOne(int[] digits) {
int last = digits.length-1;
while (last >= 0 && digits[last] == 9) {
digits[last] = 0;
last--;
}
if (last == -1) {
int[] res = new int[digits.length+1];
res[0] = 1;
return res;
}
else {
digits[last] += 1;
return digits;
}
}
}

``````