comments | difficulty | edit_url | tags | ||
---|---|---|---|---|---|
true |
简单 |
|
整数的 数组形式 num
是按照从左到右的顺序表示其数字的数组。
- 例如,对于
num = 1321
,数组形式是[1,3,2,1]
。
给定 num
,整数的 数组形式 ,和整数 k
,返回 整数 num + k
的 数组形式 。
示例 1:
输入:num = [1,2,0,0], k = 34 输出:[1,2,3,4] 解释:1200 + 34 = 1234
示例 2:
输入:num = [2,7,4], k = 181 输出:[4,5,5] 解释:274 + 181 = 455
示例 3:
输入:num = [2,1,5], k = 806 输出:[1,0,2,1] 解释:215 + 806 = 1021
提示:
1 <= num.length <= 104
0 <= num[i] <= 9
num
不包含任何前导零,除了零本身1 <= k <= 104
class Solution:
def addToArrayForm(self, num: List[int], k: int) -> List[int]:
i, carry = len(num) - 1, 0
ans = []
while i >= 0 or k or carry:
carry += (0 if i < 0 else num[i]) + (k % 10)
carry, v = divmod(carry, 10)
ans.append(v)
k //= 10
i -= 1
return ans[::-1]
class Solution {
public List<Integer> addToArrayForm(int[] num, int k) {
int i = num.length - 1, carry = 0;
LinkedList<Integer> ans = new LinkedList<>();
while (i >= 0 || k > 0 || carry > 0) {
carry += (i < 0 ? 0 : num[i--]) + k % 10;
ans.addFirst(carry % 10);
carry /= 10;
k /= 10;
}
return ans;
}
}
class Solution {
public:
vector<int> addToArrayForm(vector<int>& num, int k) {
int i = num.size() - 1, carry = 0;
vector<int> ans;
for (; i >= 0 || k || carry; --i) {
carry += (i < 0 ? 0 : num[i]) + k % 10;
ans.push_back(carry % 10);
carry /= 10;
k /= 10;
}
reverse(ans.begin(), ans.end());
return ans;
}
};
func addToArrayForm(num []int, k int) []int {
i, carry := len(num)-1, 0
ans := []int{}
for ; i >= 0 || k > 0 || carry > 0; i-- {
if i >= 0 {
carry += num[i]
}
carry += k % 10
ans = append(ans, carry%10)
carry /= 10
k /= 10
}
for i, j := 0, len(ans)-1; i < j; i, j = i+1, j-1 {
ans[i], ans[j] = ans[j], ans[i]
}
return ans
}
function addToArrayForm(num: number[], k: number): number[] {
let arr2 = [...String(k)].map(Number);
let ans = [];
let sum = 0;
while (num.length || arr2.length || sum) {
let a = num.pop() || 0,
b = arr2.pop() || 0;
sum += a + b;
ans.unshift(sum % 10);
sum = Math.floor(sum / 10);
}
return ans;
}
impl Solution {
pub fn add_to_array_form(num: Vec<i32>, mut k: i32) -> Vec<i32> {
let n = num.len();
let mut res = vec![];
let mut i = 0;
let mut sum = 0;
while i < n || sum != 0 || k != 0 {
sum += num.get(n - i - 1).unwrap_or(&0);
sum += k % 10;
res.push(sum % 10);
i += 1;
k /= 10;
sum /= 10;
}
res.reverse();
res
}
}
function addToArrayForm(num: number[], k: number): number[] {
const n = num.length;
const res = [];
let sum = 0;
for (let i = 0; i < n || sum !== 0 || k !== 0; i++) {
sum += num[n - i - 1] ?? 0;
sum += k % 10;
res.push(sum % 10);
k = Math.floor(k / 10);
sum = Math.floor(sum / 10);
}
return res.reverse();
}