LeetCode Solutions

989. Add to Array-Form of Integer

Time:

Space:

			

class Solution {
 public:
  vector<int> addToArrayForm(vector<int>& num, int k) {
    for (int i = num.size() - 1; i >= 0; --i) {
      num[i] += k;
      k = num[i] / 10;
      num[i] %= 10;
    }

    while (k > 0) {
      num.insert(begin(num), k % 10);
      k /= 10;
    }

    return num;
  }
};
			

class Solution {
  public List<Integer> addToArrayForm(int[] num, int k) {
    List<Integer> ans = new LinkedList<>();

    for (int i = num.length - 1; i >= 0; --i) {
      ans.add(0, (num[i] + k) % 10);
      k = (num[i] + k) / 10;
    }

    while (k > 0) {
      ans.add(0, k % 10);
      k /= 10;
    }

    return ans;
  }
}
			

class Solution:
  def addToArrayForm(self, num: List[int], k: int) -> List[int]:
    for i in reversed(range(len(num))):
      k, num[i] = divmod(num[i] + k, 10)

    while k > 0:
      num = [k % 10] + num
      k //= 10

    return num