DDSA
Advertisement

66. Plus One

Time: O(n)
Space: O(n)

Approach

Iterate from the last digit adding one with carry propagation. If all digits carry over, prepend 1 to a new array.

66.cs
C#
// Approach: Iterate from the last digit adding one with carry propagation.
// If all digits carry over, prepend 1 to a new array.
// Time: O(n) Space: O(n)

public class Solution
{
    public int[] PlusOne(int[] digits)
    {
        for (int i = digits.Length - 1; i >= 0; i--)
        {
            if (digits[i] < 9)
            {
                ++digits[i];
                return digits;
            }
            digits[i] = 0;
        }

        int[] ans = new int[digits.Length + 1];
        ans[0] = 1;
        return ans;
    }
}
Advertisement
Was this solution helpful?