题目描述:
对于非负整数 X 而言,X 的数组形式是每位数字按从左到右的顺序形成的数组。例如,如果 X = 1231,那么其数组形式为 [1,2,3,1]。
给定非负整数 X 的数组形式 A,返回整数 X+K 的数组形式。
示例 1:
输入:A = [1,2,0,0], K = 34
输出:[1,2,3,4]
解释:1200 + 34 = 1234
解释 2:
输入:A = [2,7,4], K = 181
输出:[4,5,5]
解释:274 + 181 = 455
示例 3:
输入:A = [2,1,5], K = 806
输出:[1,0,2,1]
解释:215 + 806 = 1021
示例 4:
输入:A = [9,9,9,9,9,9,9,9,9,9], K = 1
输出:[1,0,0,0,0,0,0,0,0,0,0]
解释:9999999999 + 1 = 10000000000
提示:
1 <= A.length <= 10000
0 <= A[i] <= 9
0 <= K <= 10000
如果 A.length > 1,那么 A[0] != 0
很简单的一道题目,需要注意的是看K位数和数组A的长度因此循环的条件需要注意一下,其余没什么特别注意的,另外就是最后的list需要反转一下
注意的是
class Solution {
public List<Integer> addToArrayForm(int[] A, int K) {
int jinwei = 0;
List<Integer> result = new ArrayList<>();
int index = A.length - 1;
while (index >=0 || K != 0) {
if(index >= 0){
int tem = K % 10;
K = K/10;
result.add(((tem+A[index] + jinwei)% 10));
jinwei =(tem+A[index] + jinwei) / 10;
index --;
}else {
int tem = K % 10;
K = K/10;
result.add(((tem + jinwei)% 10));
jinwei =(tem + jinwei) / 10;
}
}
if(jinwei == 1){
result.add(jinwei);
}
Collections.reverse(result);//反转一下list
return result;
}
}