# 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.

_*Example_8

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

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

Tags

Related Problems

Medium Divide Two Integers 15 % Easy Add Binary

## Solution

``````public class Solution {
/**
* @param digits a number represented as an array of digits
* @return the result
*/
public int[] plusOne(int[] digits) {
int carries = 1;
for (int i = digits.length - 1; i >= 0 && carries > 0; i--) {
int sum = digits[i] + carries;
digits[i] = sum % 10;
carries = sum / 10;
}
if (carries == 0) {
return digits;
}
int[] result = new int[digits.length + 1];
result[0] = 1;
for (int i = 1; i < result.length; i++) {
result[i] = digits[i - 1];
}
return result;
}
}``````

``````class Solution {
public int[] plusOne(int[] digits) {
int carry = 0;
int i = digits.length - 1;
while (carry >= 0 && i >= 0) {
int tmp = 0;
if (i == digits.length - 1) {
tmp = 1 + digits[i] + carry;
} else {
tmp = digits[i] + carry;
}
if (tmp > 9) {
digits[i] = tmp % 10;
carry = 1;
} else {
digits[i] = tmp;
carry = 0;
}
i--;
}
int[] ans;
if (carry > 0) {
ans = new int[digits.length + 1];
ans[0] = carry;
for (int k = 1; k < ans.length; k++) {
ans[k] = digits[k - 1];
}
} else {
ans = digits;
}
return ans;
}
}``````

Last updated