# LeetCode Plus One: Math Array Simulation

## Overview

LeetCode Plus One: Math Simulation of plus one by array, just simulate the process of adding one and handle both sum and carry carefully.

## LeetCode Plus One

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 and Precautions: Math Array Simulation

This is quite a simple problem of simulating the plus operation, just practice your knowledge of how to do addition (carry, digit concepts) and don’t forget special case like 999+1 = 10000. The following java code is accepted by the LeetCode OJ to pass this Plus One problem:

```public class Solution {

public int[] plusOne(int[] digits) {
List<Integer> ret = new ArrayList<Integer>();
int sum = 0;
int carry = 1;

int n = digits.length;

for (int i = n - 1; i >= 0; --i) {
sum = digits[i] + carry;
carry = sum / 10;
sum %= 10;
}

if (carry > 0)
Collections.reverse(ret);
int [] results = new int[ret.size()];

for (int i = ret.size() - 1; i >= 0; --i)
results[i] = ret[i].intValue();

return results;
}
}
```

## Summary

LeetCode Plus One: Math Simulation of plus one by array, just simulate the process of adding one and handle both sum and carry carefully.

Written on April 18, 2013