Skip to content

989. Add to Array-Form of Integer 👍

  • Time:
  • Space:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
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;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
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;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
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