/**
* 要求"return the array-form of the integer",但返回类型是List<Integer>就离谱
* 自己的代码
* 有一些自己觉得写的很妙的地方:
* 1. 不单独处理进位,每次将sum产生的进位在循环的最后加到k里
* 2. 第一个for循环后不判断k是否变为0再区分行为,直接将k中的位加入resList,如果k已经为0,自动不会进入循环(且过程中每取一位要将其插在resList的头部,而非接在后面)
* Runtime: 2 ms, faster than 99.81%
* Memory Usage: 41.1 MB, less than 37.38%
*/
class Solution {
public List<Integer> addToArrayForm(int[] num, int k) {
List<Integer> res = new LinkedList();
// calculate all digits in num
for (int i = num.length - 1; i >= 0 && k > 0; i--) {
int sum = num[i] + k % 10;
num[i] = sum % 10;
k = k / 10 + sum / 10; // add carry bits to k
}
// add remained k to resList until k become 0 (k is possible to be 0 when existing the first for-loop)
for ( ; k != 0; k /= 10) {
res.add(0, k % 10);
}
// add every digit in the calculated num array to resList
for (int i : num) {
res.add(i);
}
return res;
}
}