Add to Array-Form of Integer
数组相加. 先把k变成数组格式, 然后想加. 最后再翻转数组.
class Solution {
public List<Integer> addToArrayForm(int[] A, int K) {
List<Integer> res = new ArrayList<Integer>();
int[] B = toArray(K);
int carry = 0;
int i = A.length - 1;
int j = B.length - 1;
while(i >= 0 && j >= 0) { // add both
int sum = carry + A[i] + B[j];
res.add(sum % 10);
carry = sum / 10;
i--;
j--;
}
while(i >= 0) { // add rest of A
int sum = carry + A[i];
res.add(sum % 10);
carry = sum / 10;
i--;
}
while(j >= 0) { // add rest of B
int sum = carry + B[j];
res.add(sum % 10);
carry = sum / 10;
j--;
}
if(carry != 0) // add carry if still have carry
res.add(carry);
Collections.reverse(res); // reverse
return res;
}
private int[] toArray(int K) { // to array form
String s = String.valueOf(K);
int[] res = new int[s.length()];
for(int i = res.length-1; i >= 0; i--) {
res[i] = s.charAt(i) - '0';
}
return res;
}
}