Categories:

Tags:



Problem

The array-form of an integer num is an array representing its digits in left to right order.

  • For example, for num = 1321, the array form is [1,3,2,1].

Given num, the array-form of an integer, and an integer k, return the array-form of the integer num + k.

Constraints

  • 1 <= num.length <= 104
  • 0 <= num[i] <= 9
  • num does not contain any leading zeros except for the zero itself.
  • 1 <= k <= 104

Solution

The problem Add to Array-Form of Integer can be solved by adding each digits of num and k to create a new array-form of an integer.

Implementation

static const int fast_io = []()
{
    std::ios::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    return 0;
}();

class Solution
{
  public:
    vector<int> addToArrayForm(vector<int> &num, int k)
    {
        int carry = 0;
        int idx = num.size();

        vector<int> ret;
        do
        {
            int sum = (idx-- > 0 ? num[idx] : 0) + (k % 10) + carry;
            ret.push_back(sum % 10);
            carry = sum / 10;
        } while ((k /= 10) || carry || idx > 0);

        reverse(ret.begin(), ret.end());
        return ret;
    }
};