Problem : https://leetcode.com/problems/add-to-array-form-of-integer/description/
Add digit on each position from back.
Time complexity = O (max(len(num), log(k))
class Solution {
public List<Integer> addToArrayForm(int[] num, int k) {
LinkedList<Integer> result = new LinkedList<>();
int carry = 0;
int i = num.length - 1;
while (i >= 0 || k > 0 || carry != 0) {
int a = k % 10;
int b = i >= 0 ? num[i--] : 0;
k /= 10;
result.addFirst((a + b + carry) % 10);
carry = (a + b + carry) / 10;
}
return result;
}
}
No comments:
Post a Comment