Categories:

Tags:



Problem

You are given a large integer represented as an integer array digits, where each digits[i] is the ith digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading 0’s.

Increment the large integer by one and return the resulting array of digits.

Constraints

  • 1 <= digits.length <= 100
  • 0 <= digits[i] <= 9.
  • digits does not contain any leading 0’s.

Solution

The problem Plus One can be solved by implementing a full adder and applying it through the digits given.

Implementation

class Solution
{
  public:
    vector<int> plusOne(vector<int> &digits)
    {
        for (int i = digits.size(); i > 0; i--)
        {
            digits[i - 1] = digits[i - 1] == 9 ? 0 : digits[i - 1] + 1;
            if (digits[i - 1] != 0)
                break;
        }

        if (digits[0] == 0)
            digits.insert(digits.begin(), 1);

        return digits;
    }
};