πŸ“ Problem Details

πŸ’­What Were My Initial Thoughts?

- convert each number in the array into a character and append the character into a string variable
- convert the string into an integer
- add k to the integer
- convert back into a string
- for each char in the string, push it into a results vector
- return the results vector

this works but encounters runtime errors with numbers that exceed integer max size or even long sizes

πŸ€”What Did I Struggle With?

~

πŸ’‘ Explanation of Solution

- iterate through the array from back to front
- create a column variable in order to do column addition
- push back the sum of the current element and the carry element
- if it exceeds a value of 9, then use the mod operator to only push the last digit and append carry
- reverse the result vector and return it 

βŒ› Complexity Analysis

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

πŸ’» Implementation of Solution

class Solution {
public:
    vector<int> addToArrayForm(vector<int>& num, int k) {
        vector<int> result;
 
        int i = num.size() -1;
        int carry = k;
 
        // process digits from the end and add k
        while(i >= 0 || carry > 0) {
            
            if(i >= 0) {
                carry += num[i]; // add current digit to carry
                i--;
            }
 
            result.push_back(carry % 10); // take the last digit
            carry /= 10; // update carry
        }
 
        // reverse the result to get the correct order
        reverse(result.begin(), result.end());
        return result;
    }
};