意见箱
恒创运营部门将仔细参阅您的意见和建议,必要时将通过预留邮箱与您保持联络。感谢您的支持!
意见/建议
提交建议

LeetCode-Add to Array-Form of Integer

来源:恒创科技 编辑:恒创科技编辑部
2024-02-03 07:57:59


Description:
For a non-negative integer X, the array-form of X is an array of its digits in left to right order. For example, if X = 1231, then the array form is [1,2,3,1].

Given the array-form A of a non-negative integer X, return the array-form of the integer X+K.


LeetCode-Add to Array-Form of Integer

Example 1:

Input: A = [1,2,0,0], K = 34
Output: [1,2,3,4]
Explanation: 1200 + 34 = 1234

Example 2:

Input: A = [2,7,4], K = 181
Output: [4,5,5]
Explanation: 274 + 181 = 455

Example 3:

Input: A = [2,1,5], K = 806
Output: [1,0,2,1]
Explanation: 215 + 806 = 1021

Example 4:

Input: A = [9,9,9,9,9,9,9,9,9,9], K = 1
Output: [1,0,0,0,0,0,0,0,0,0,0]
Explanation: 9999999999 + 1 = 10000000000

Note:

1 <= A.length <= 100000 <= A[i] <= 90 <= K <= 10000If A.length > 1, then A[0] != 0

题意:给定一个数组A,里面每个元素的范围在[0, 9];和一个整数K,对数组A执行累加K的操作,从最低为开始执行加法,并保证相加后每一位的范围仍在[0, 9];

解法:其实就是让我们实现一个大数加法,只不过现在一个以数组的形式给出,一个直接给出整数;定义最终的返回结果为res;
第一步:同时从A和K的最低位开始遍历,存储相加后的结果到res中(注意:需要添加在首部,因此我们利用LinkedList实现);
第二步:完成第一步后会有两种可能的情况:
1)如果数组A遍历完后,K依然大于0,此时需要将余下的K添加到res中
2)如果此时进位不为0,那么也需要添加到res中

Java
class Solution {
public List<Integer> addToArrayForm(int[] A, int K) {
LinkedList<Integer> res = new LinkedList<>();
int carry = 0;
for (int i = A.length - 1; i >= 0; i--) {
int x = A[i] + carry + K % 10;
carry = x / 10;
x %= 10;
K /= 10;
res.addFirst(x);
}
while (K > 0) {
int x = carry + K % 10;
carry = x / 10;
x %= 10;
K /= 10;
res.addFirst(x);
}
if (carry > 0) {
res.addFirst(carry);
}

return res;
}
}


上一篇: LeetCode-Find Duplicate File in System 下一篇: 手机怎么远程登录云服务器?