Open azl397985856 opened 2 years ago
思路: 创建一个out数组用于存放结果。 pre代表进位,sum代表总和,k代表被加数 数组从n-1到0开始遍历, 但是for的判断条件有i>=0||k>0||pre>0 如果i>=0,则 sum= num[i]+k%10+pre 否则 sum= k%10+pre 最后处理:pre = sum/10; k /= 10 添加到out数组 最后翻转数组即可
func addToArrayForm(num []int, k int) []int {
n := len(num)
pre,sum:=0,0
out := []int{}
for i:=n-1;i>=0||k>0||pre>0;i--{
if i >= 0{
sum = num[i]+k%10+pre
}else{
sum =k%10 + pre
}
pre = sum/10
k /= 10
out = append(out,sum%10)
}
reverse(out)
return out
}
func reverse(out []int) []int{
for i:=0;i<len(out)/2;i++{
out[i],out[len(out)-1-i] = out[len(out)-1-i] , out[i]
}
return out
}
时间复杂度O(n) 空间复杂度O(n)
模拟,将num和k从个位起逐位相加,最终然后反转vector即可。
例如:
num = [1, 2, 3, 4]
k = 12
-->ans = [6]
-->ans = [6, 4]
-->ans = [6, 4, 2]
-->ans = [6, 4, 2, 1]
-->ans = [1, 2, 4, 6]
class Solution {
public:
vector<int> addToArrayForm(vector<int>& num, int k) {
vector<int> ans;
int n = num.size() - 1;
int flag = 0;
while(n >= 0 || k != 0){
int a = n < 0 ? 0 : num[n];
int b = k != 0 ? (k % 10) : 0;
int tmp = a + b + flag;
ans.push_back(tmp % 10);
flag = tmp / 10;
--n; k/=10;
}
if(flag != 0){
ans.push_back(flag);
}
reverse(ans.begin(), ans.end());
return ans;
}
};
复杂度分析
思路: 从后往前遍历数组,k+num[i]的模就为结果数组的前一位,k /= 10 存在遍历结束k还大于0的情况,用k/=10处理
class Solution {
public List<Integer> addToArrayForm(int[] num, int k) {
List<Integer> ans = new ArrayList<>();
int i = num.length - 1;
while (i >= 0 || k > 0) {
if (i >= 0) {
k = num[i] + k;
}
ans.add(0, k % 10);
k/= 10;
i--;
}
return ans;
}
}
时间O(n) 空间O(n)
将K的每位与A的每位相加,如果大于10,则下一次相加要进位。
/**
* @param {number[]} num
* @param {number} k
* @return {number[]}
*/
var addToArrayForm = function (num, k) {
let answer = [];
let carry = 0; // 进位
for (let i = 1; i <= num.length || k >= 1; i++) {
let num1 = num.length - i >= 0 ? num[num.length - i] : 0;
let num2 = k % 10;
let sum = num1 + num2 + carry; //每位的和记得加上上一位的进位
if (sum >= 10) {
answer.unshift(sum % 10);
carry = Math.floor(sum / 10)
} else {
answer.unshift(sum)
carry = 0
}
k = Math.floor(k / 10)
}
if (carry !== 0) { // 出循环后,如果最后进位不为0,则将进位添加到数组首位
answer.unshift(carry)
}
return answer;
};
复杂度分析不是很会,不一定对,如果有错,请指正。
class Solution:
def addToArrayForm(self, num: List[int], k: int) -> List[int]:
# numSum = 0
# for n in num:
# numSum = numSum*10+n
# numSum += k
# return list(str(numSum))
return (list(str(int("".join(map(str, num))) + k)))
时间复杂度: O(n)
空间复杂度: O(n)
https://leetcode-cn.com/problems/add-to-array-form-of-integer/
基本的加减法思路,从最低位开始,逐位相加,大于10就进1位(直接在原数k上操作),把结果存到一个新的数组res中, 如果最后k仍然大于0,说明最终结果位数大于两个加数,这时候再将k值加到结果数组res中, 最后再翻转该数组即可得到最终结果。
class Solution {
public:
vector<int> addToArrayForm(vector<int>& num, int k) {
vector<int> res;
int n = num.size();
for(int i = n-1;i >= 0;i--)
{
int temp = num[i] + k % 10;
k /= 10;
if(temp >= 10)
{
k++;
temp -= 10;
}
res.push_back(temp);
}
while(k > 0)
{
res.push_back(k % 10);
k /= 10;
}
reverse(res.begin(), res.end());
return res;
}
};
复杂度分析
class Solution:
def addToArrayForm(self, num: List[int], k: int) -> List[int]:
ans, i = [],len(num) -1
while k > 0 or i >= 0:
k,rmd = divmod(k + (num[i] if i >= 0 else 0),10)
ans.append(rmd)
i -= 1
return reversed(ans)
class Solution:
def addToArrayForm(self, num: List[int], k: int) -> List[int]:
carry = 0
ans = collections.deque()
while num or k>0 or carry > 0:
last = num.pop() if num else 0
cur = (carry + last + k%10)%10
carry = (carry + last + k%10)//10
k = k//10
ans.appendleft(cur)
return ans
Time: O(max(N, log_10(K)). N is the length of num array. Since we divide K by 10 every loop till K is zero, the complexity of this operation will be log base 10 of K. Sapce: O(1). The space for carry, last is O(1). The space for the ans is O(max(N, log_10(K)).
### 代码
class Solution:
def addToArrayForm(self, num: List[int], k: int) -> List[int]:
i = len(num)-1
while k > 0:
num[i] += k
k, num[i] = num[i] // 10, num[i] % 10
i -= 1
if i < 0 and k!= 0:
num.insert(0, 0)
i = 0
return num
思路:
复杂度分析:
代码(C++):
class Solution {
public:
vector<int> addToArrayForm(vector<int>& num, int k) {
int n = num.size() - 1;
vector<int> res;
while (n >= 0) {
k += num[n];
res.push_back(k % 10);
k /= 10;
n--;
}
// for the condition that k not 0
while (k) {
res.push_back(k % 10);
k /= 10;
}
reverse(res.begin(), res.end());
return res;
}
};
把数组num转换成整数,与k相加,再将得到的和转换成对应的数组
class Solution(object):
def addToArrayForm(self, num, k):
"""
:type num: List[int]
:type k: int
:rtype: List[int]
"""
nn=0
'''
for i in reversed(range(len(num))):
nn = nn + 10 ** (len(num) - 1 - i) * num[i]
'''
for n in num:
nn = nn*10+n
sum=nn+k
strs=str(sum)
l=[]
for j in range(len(strs)):
l.append(int(strs[j]))
return l
时间复杂度:O(N),N是num+k的位数 空间复杂度:O(N)
C++ Code:
class Solution {
public:
vector<int> addToArrayForm(vector<int>& num, int k) {
int i=num.size()-1;
int carry =0;
vector<int> ret;
while(k||carry||i<num.size())
{
int value ;
if(i>=0)
{
value = k%10 + num[i] + carry;
}
else
{
value = k%10 + carry;
}
carry = value/10;
ret.push_back(value%10);
k = k/10;
i--;
}
reverse(ret.begin(), ret.end());
return ret;
}
};
class Solution {
public List<Integer> addToArrayForm(int[] num, int k) {
int len = num.length;
int count = 0;
int flag = 0;
List<Integer> ans = new ArrayList<>();
while (k > 0) {
int tmpNum = len - count - 1 < 0 ? 0: num[len - count - 1];
int sum = k % 10 + tmpNum + flag;
flag = sum / 10;
k /= 10;
count++;
ans.add(flag == 1 ? sum % 10 : sum);
}
for(int i = len - count - 1; i > -1; i--) {
int sum = num[i] + flag;
flag = sum / 10;
ans.add(flag == 1 ? sum % 10 : sum);
}
if (flag == 1) {
ans.add(1);
}
Collections.reverse(ans);
return ans;
}
}
traverse each digit of the num
and k
in reverse order and do add operation
reverse the list and return
class Solution {
public List<Integer> addToArrayForm(int[] num, int k) {
int carry = 0;
int p = num.length - 1;
List<Integer> list = new LinkedList<>();
while( p >= 0 || k > 0 || carry > 0) {
int cur = k % 10 + carry;
if(p >= 0) {
cur += num[p];
p--;
}
list.add(cur % 10);
carry = cur / 10;
k = k / 10;
}
Collections.reverse(list);
return list;
}
}
复杂度分析
class Solution {
public List<Integer> addToArrayForm(int[] A, int K) {
List<Integer> res = new ArrayList<Integer>();
int n = A.length;
for(int i = n - 1;i >= 0;i--){
int sum = A[i] + K % 10;
K /= 10;
if(sum >= 10){
K++;
sum -= 10;
}
res.add(sum);
}
while (K > 0) {
res.add(K % 10);
K /= 10;
}
Collections.reverse(res);
return res;
}
}
class Solution {
public List<Integer> addToArrayForm(int[] num, int k) {
// first, int to array
List<Integer> list = new ArrayList<>();
while (k > 0) {
list.add(k % 10);
k = k / 10;
}
// ge shi bai....
// bai shi ge...
int i = num.length - 1;
int j = 0;
int carry = 0;
List<Integer> result = new ArrayList<>();
while (i >= 0 && j <= list.size() - 1) {
int temp = num[i] + list.get(j) + carry;
result.add(temp % 10);
carry = temp / 10;
i--;
j++;
}
while (i >= 0) {
int temp = num[i] + carry;
result.add(temp % 10);
carry = temp / 10;
i--;
}
while (j <= list.size() - 1) {
int temp = list.get(j) + carry;
result.add(temp % 10);
carry = temp / 10;
j++;
}
if (carry != 0) {
result.add(carry);
}
Collections.reverse(result);
return result;
}
}
class Solution:
def addToArrayForm(self, num: List[int], k: int) -> List[int]:
num1 = int(''.join(map(str,num)))
return list(map(int,list(str(num1+k))))
Calculate the total sum in the array, each number * 10^idx. Then sum up with the k Out each digit in the total sum
class Solution(object):
def addToArrayForm(self, num, k):
"""
:type num: List[int]
:type k: int
:rtype: List[int]
"""
idx = len(num) - 1
sum_num = 0
res = []
for number in num:
sum_num = number * (10**idx) + sum_num
idx -= 1
sum_num += k
for digit in (str(sum_num)):
res.append(int(digit))
return res
复杂度分析
class Solution:
def addToArrayForm(self, num: List[int], k: int) -> List[int]:
num2 = list()
while k:
tmp = k % 10
num2.append(tmp)
k //= 10
num2.reverse()
i, j = len(num) - 1, len(num2) - 1
isCarried = False
res = list()
while i >= 0 or j >= 0 or isCarried:
digit = (num[i] if i >= 0 else 0) + (num2[j] if j >= 0 else 0) + (1 if isCarried else 0)
isCarried = True if digit >= 10 else False
res.append(digit % 10)
i -= 1
j -= 1
res.reverse()
return res
Time Complexity: O(n), Space Complexity: O(n)
class Solution(object):
def addToArrayForm(self, num, k):
"""
:type num: List[int]
:type k: int
:rtype: List[int]
"""
def num_to_lst(n):
result = []
while n:
result.append(n % 10)
n = n // 10
return result[::-1]
k_lst = num_to_lst(k)
i = len(num) - 1
j = len(k_lst) - 1
result = []
carry = 0
while i >= 0 or j >= 0 or carry:
left = num[i] if i >= 0 else 0
right = k_lst[j] if j >= 0 else 0
s = left + right + carry
result.append(s % 10)
carry = s // 10
i -= 1
j -= 1
return result[::-1]
Time: O(max(n, m)) Space: O(n)
func addToArrayForm(num []int, k int) (ans []int) {
// 考虑直接相加k
for i := len(num) - 1; i >= 0 || k > 0; i-- {
if i >= 0 {
k += num[i]
}
ans = append(ans, k % 10)
k /= 10
}
reverse(ans)
return
}
// 反序的时候,直接头与尾相交换
func reverse(num []int){
for i, n := 0, len(num); i < n/2; i++ {
num[i], num[n-1-i] = num[n-1-i], num[i]
}
}
class Solution {
public List<Integer> addToArrayForm(int[] num, int k) {
LinkedList<Integer> ans = new LinkedList<>();
int sum = 0, carry = 0, len = num.length - 1;
while (len >= 0 || k != 0) {
int x = len >= 0 ? num[len] : 0;
int y = k != 0 ? k % 10 : 0;
sum = x + y + carry;
carry = sum / 10;
k /= 10;
len --;
ans.addFirst(sum % 10);
}
if (carry != 0) ans.addFirst(carry);
return ans;
}
}
class Solution {
// 取 k 的最后一位 lastOfk
// 取 num 的最后一位 lastOfNum
// 如果 sum(lastOfNum + lastOfk + flag) 大于等于10,进位标记为1,将 sum(lastOfNum + lastOfk + flag) % 10 放置到 res 中
// 如果 sum(lastOfNum + lastOfk + flag) 小于10, 进位标记为0,将 sum(lastOfNum + lastOfk + flag) % 10 放置到 res 中
// 然后遍历完 num, k 并确保flag最后的值为 0
public List<Integer> addToArrayForm(int[] num, int k) {
LinkedList<Integer> res = new LinkedList<>();
// 遍历k
int index = num.length - 1; // num 的最后一位
int flag = 0; // 进位
int lastOfNum = 0;
int lastOfk = 0;
int sum = 0;
while (k > 0 && index >= 0) {
lastOfk = k % 10;
k /= 10;
lastOfNum = num[index--];
sum = lastOfk + lastOfNum + flag;
if (sum >= 10) {
flag = 1;
res.addFirst(sum % 10);
} else {
flag = 0;
res.addFirst(sum);
}
}
while (k > 0) {
lastOfk = k % 10;
k /= 10;
sum = lastOfk + flag;
if (sum >= 10) {
flag = 1;
res.addFirst(sum % 10);
} else {
flag = 0;
res.addFirst(sum);
}
}
while (index >= 0) {
lastOfNum = num[index--];
sum = lastOfNum + flag;
if (sum >= 10) {
flag = 1;
res.addFirst(sum % 10);
} else {
flag = 0;
res.addFirst(sum);
}
}
if (flag == 1) {
res.addFirst(1);
}
return res;
}
}
Ripple Adder Similar to the implementation of ripple adder, The adder will add numbers at the same position, output the sum of the current position, and pass the carry to the next bit.
Python class Solution: def addToArrayForm(self, A: List[int], k: int) -> List[int]: curSum = 0 carry = 0
# This can be achieved through continuing division, but I am lazy
if not A:
return [int(i) for i in str(k)]
elif not k:
return A
K = [int(i) for i in str(k)]
LA = len(A)-1
LK = len(K)-1
if LA <= LK:
target = K
idx = LK
else:
target = A
idx = LA
while LA >= 0 and LK >= 0:
curSum = A[LA] + K[LK] + carry
if curSum < 10:
target[idx] = curSum
carry = 0
else:
carry = curSum //10
target[idx] = curSum % 10
LA-=1
LK-=1
idx-=1
if LK != LA:
while idx >=0:
curSum = target[idx] + carry
if curSum < 10:
target[idx] = curSum
carry = 0
else:
carry = curSum // 10
target[idx] = curSum%10
idx-=1
if carry > 0:
target[0:0] = [carry]
return target
Time Complexity: O(max(K,A)) Space Complexity: O(max(K,A))
思路 数组尾数与k 逐项相加,大于10 则进位
代码
var add = function(num, k) { const res = []; const len = num.length; for (let i = len - 1; i >= 0; --i) { let sum = num[i] + k % 10; k = Math.floor(k / 10); if (sum >= 10) { k++; sum -= 10; } res.push(sum); } for (; k > 0; k = Math.floor(k / 10)) { res.push(k % 10); } res.reverse(); return res; };
复杂度分析
1. 创造一个空列表,用来存储结果
2. 取出num列表的每一个数字,按照位次和K对应的位次相加,如果超过10就进位,获得num和k在每一个位次上的和
3. 将每一位次的和按照相应的顺序append到list中,就得到结果
class Solution {
public List
}
}
**复杂度分析**
- 时间复杂度:O(max(O, logk))
- 空间复杂度:O(1)
思路: 首先设立一个存放答案的切片。 接着让数据数组从最后一位开始向前遍历,同时与k数的余数相加。 相加完判断该值的大小,如果大于十输入到答案切片的时候要减十。 最后再对答案切片做一个反转。
func addToArrayForm(num []int, k int) []int {
ans := make([]int,0)
for i := len(num) - 1; i >=0; i -- {
tem := num[i] + k % 10
k = k / 10
if tem >= 10 {
ans = append(ans,tem - 10)
k ++
}else {
ans = append(ans,tem )
}
}
for ; k > 0; k /= 10 {
ans = append(ans, k%10)
}
reverse(ans)
return ans
}
func reverse(num []int) {
for i, n := 0, len(num); i < n/2; i++ {
num[i], num[n-1-i] = num[n-1-i], num[i]
}
}
-- java版
class Solution {
public List<Integer> addToArrayForm(int[] num, int k) {
List<Integer> res = new ArrayList<Integer>();
int n = num.length;
for(int i=n-1; i>=0; --i){
k += num[i];
res.add(k % 10);
k = k /10;
}
for(; k>0; k/=10){
res.add(k%10);
}
Collections.reverse(res);
return res;
}
}
-- python版
class Solution:
def addToArrayForm(self, num: List[int], k: int) -> List[int]:
res = []
for i in range(len(num)-1, -1, -1):
k += num[i]
res.insert(0, k%10)
k //= 10
while k:
res.insert(0, k%10)
k //= 10
return res
class Solution:
def addToArrayForm(self, num: List[int], k: int) -> List[int]:
res = []
for n in num[::-1]:
k += n
res.insert(0, k%10)
k //= 10
while k:
res.insert(0, k%10)
k //= 10
return res
说到底还是遍历,时间复杂度:O(max(k的位数, len(num)))
思路: Adding up by digits. In the array, we start from the very end element. For the integer k, each time we use the last digit (k % 10), if the sum is bigger than 9, add 1 to k(so we don't need another var to record it). After the loop, deal with the case k > 0 (maybe k is too big or we have addup).
代码
class Solution {
public List<Integer> addToArrayForm(int[] num, int k) {
List<Integer> res = new ArrayList<>();
int n = num.length;
for (int i = n - 1; i >= 0; i--) {
int sum = num[i] + k % 10;
k /= 10;
if (sum > 9) {
k += 1;
sum -= 10;
}
res.add(sum);
}
for (; k > 0; k /= 10) {
res.add(k % 10);
}
Collections.reverse(res);
return res;
}
}
Time Complexity Time: O(n), one for loop; Space: O(n), use one arraylist
思路:使用数列式两数相加模板,注意carry 的进位和取模操作
class Solution: def addToArrayForm(self, num: List[int], k: int) -> List[int]: p1 = len(num) -1 carry = 0 results = [] while p1 >=0 or k != 0 or carry>0: add1 = num[p1] if p1 >=0 else 0 add2 = k %10 sum = add1 + add2 + carry carry = 1 if sum >= 10 else 0 sum = sum - 10 if sum >= 10 else sum results.append(sum) p1 -= 1 k //= 10 return results[::-1]
时间复杂度 O(N) 空间复杂度 O(N)
思路:
各位相加,从低到高位计算。nums数组从nums.length-1的位置开始遍历,每次遍历都与当前k的个位值相加,并加上当前一个进位值, 在判断是否大于9,更新进位值。
细节处理:当k的位数大于nums.length时,在遍历完nums数组后还要处理剩下的k,直到k为0。如果最后进位值为一,要在ans数组头部加1。
代码:
class Solution {
public List<Integer> addToArrayForm(int[] num, int k) {
List<Integer> ans = new LinkedList<Integer>();
int jinwei = 0;
for(int i = num.length - 1;i >= 0;i--){
int a = num[i] + (k % 10) + jinwei;
if(a >= 10){
jinwei = 1;
a %= 10;
}
else{
jinwei = 0;
}
ans.add(0,a);
k = k / 10;
}
while(k != 0){
if(jinwei != 0){
int a = (k % 10) + jinwei;
if(a >= 10){
jinwei = 1;
a %= 10;
}
else{
jinwei = 0;
}
ans.add(0, a);
}
else{
ans.add(0, k % 10);
}
k = k / 10;
}
if(jinwei != 0){
ans.add(0,1);
}
return ans;
}
}
复杂度
时间复杂度:O(max(nums.length,len(k))),因为List是用LinkedList实现,所以在链表头部插入元素的时间复杂度为O(1)。
空间复杂度:O(ans.size())。
const addToArrayForm = (num, k) => {
const result = []
let carry = 0 // 是否进位
for(let i = num.length - 1; i >= 0 || k > 0; i--) {
const numItem = num[i] || 0
let sum = numItem + (k % 10) + carry
if (sum >= 10) {
sum = sum - 10
carry = 1
} else {
carry = 0
}
k = Math.floor(k / 10)
result.push(sum)
}
if (carry === 1) {
result.push(1)
}
return result.reverse()
};
M是num的长度, N是k的长度
思路: 从最后一位开始,模拟竖式加法,逐位向前求和。
class Solution:
def addToArrayForm(self, num: List[int], k: int) -> List[int]:
n = len(num)
p = n - 1
carry = 0
while k > 0 or p >= 0:
last = k % 10
new = carry + last + (num[p] if p >= 0 else 0)
if p >= 0:
num[p] = new % 10
else:
num.insert(0, new % 10)
carry = new // 10
k = k // 10
p = p - 1
if carry == 1:
num.insert(0, 1)
return num
遍历合并,类似合并有序数组/链表。
var addToArrayForm = function(num, k) {
ans = [];
i = num.length - 1;
carry = 0;
while (i >= 0 || k != 0) {
val1 = i >= 0 ? num[i] : 0;
val2 = k != 0 ? k % 10 : 0;
sum = val1 + val2 + carry;
carry = Math.floor(sum / 10);
sum = sum % 10;
ans.push(sum);
i--;
k = Math.floor(k/10);
}
if (carry != 0) {
ans.push(carry);
}
return ans.reverse();
};
TC: O(max(N, logK)) SC: O(max(N, logK))
题型:模拟 思路:模拟加法运算,大于或等于 10 就向前进位
function addToArrayForm(num: number[], k: number): number[] {
let carry = 0; // 记录进位
let i = num.length - 1; // 记录当前 num 数字的指针
const res = []; // 结果
// 当 i >= 0 或 k > 0 或 carry > 0 的时候,说明需要继续进行加法
while(i >= 0 || k > 0 || carry > 0) {
const k_add = k > 0 ? k % 10 : 0; // k 提供的加数
const num_add = i >= 0 ? num[i] : 0; // num 提供的加数
const sum = k_add + num_add + carry; // 求和
res.push(sum % 10); // 存储结果
carry = Math.floor(sum / 10); // 计算进位
i--;
k = Math.floor(k / 10);
}
return res.reverse();
};
时间:O(max(n, m)) 空间:O(n)
本来的思路是直接算,然后翻转,遇到几个问题
class Solution {
public List<Integer> addToArrayForm(int[] num, int k) {
List<Integer> result = new ArrayList<>();
for(int i = num.length - 1; i >= 0; i--) {
int temp = (num[i] + k) % 10;
k = (k + num[i])/10;
result.add(temp);
}
while(k!=0) {
result.add(k%10);
k = k/10;
}
Collections.reverse(result);
return result;
}
}
复杂度分析
class Solution {
public List<Integer> addToArrayForm(int[] nums, int k) {
LinkedList<Integer> res = new LinkedList<>(); // LinkedList addFirst()
for (int i = nums.length - 1; i >= 0; i --) {
res.addFirst((nums[i] + k) % 10);
k = (nums[i] + k) / 10;
}
while (k > 0) {
res.addFirst(k % 10);
k /= 10;
}
return res;
}
}
//Time O(n), Space O(n)
··· class Solution: def addToArrayForm(self, num: List[int], k: int) -> List[int]: n = len(num) A = 0 for i,a in enumerate(num): A += a*(10**(n-i-1)) ans = A+k
res = [int(s) for s in str(ans)]
return res
··· 时间复杂度:O(n) 空间复杂度:O(n)
思路 大整数的存储 从高位到低位存,方便进位 例:123456789 -> [9, 8, 7, 6, 5, 4, 3, 2, 1]
相加 用代码模拟两数相加 [A3, A2, A1, A0] + [B2, B1, B0] -> C0 = A0 + B0 如果 C0 > 10,则进位 -> C1 = A1 + B1 + t(有进位则为1,否则为0) -> C2 = A2 + B2 + t -> C3 = A2 + t
TS语法部分 TS中的Number数据类型并不是int,所以在取余数的时候,要额外做取整
代码
function addToArrayForm(num: number[], k: number): number[] { num.reverse(); for (let i = 0; i < num.length; i++) { k += num[i]; num[i] = k % 10; k = (k / 10) | 0; } while (k > 0) { num.push(k % 10); k = (k / 10) | 0; } num.reverse(); return num; }
分析 时间复杂度:O(n) 空间复杂度:O(1)
代码1 初始版本,除了代码短,没有优点。执行用时:4928 ms, 在所有 Python3 提交中击败了6.65%的用户,内存消耗:15.6 MB, 在所有 Python3 提交中击败了27.26%的用户。
class Solution:
def addToArrayForm(self, num: List[int], k: int) -> List[int]:
len_A=len(num)
sum=0
sum_a=0
for i in range(len_A):
sum_a=sum_a+num[i]*pow(10,(len_A-1-i))
sum=sum_a+k
result=list(map(int, str(sum)))
return result
var addToArrayForm = function(A, K) { const res = []; const n = A.length; for (let i = n - 1; i >= 0 || K > 0; --i, K = Math.floor(K / 10)) { if (i >= 0) { K += A[i]; } res.push(K % 10); } res.reverse(); return res; };
// train of thought:
// Add up each number.Then fill the next one
// the first step is traverse the array ,then the index value add then k of index number.
// the second step is check boundary condition to ensure all numbers added.because num's array size is correct, but not sure k is correct
// the third step is reversing array
// complexity analysis:O(n)
class Solution {
public:
vector<int> addToArrayForm(vector<int>& num, int k) {
vector<int> res;
int size = num.size();
for(int n = size - 1; n >= 0; n--) {
int sum = num[n] + k % 10;
k /= 10;
if (sum >= 10) {
// for next loop to complement
k++;
sum = sum % 10;
}
res.push_back(sum);
}
for (; k > 0; k /= 10) {
res.push_back(k % 10);
}
reverse(res.begin(), res.end());
return res;
}
};
class Solution {
public List<Integer> addToArrayForm(int[] num, int k) {
int[] cur = new int[num.length + 5];
int i = num.length - 1, j = 0;
for (; i >= 0; i--, j++) {
cur[j] = (k + num[i]) % 10;
k = (k + num[i]) / 10;
}
while (k != 0) {
cur[j++] = k % 10;
k = k / 10;
}
ArrayList<Integer> result = new ArrayList<Integer>();
for (int indexR = 0, indexCur = j - 1; indexR < j; indexR++, indexCur--) {
result.add(cur[indexCur]);
}
return result;
}
}
时间复杂度:2次遍历数组,时间复杂度为O(N)
空间复杂度:O(N)
N 为 数组长度或K的最大值。
class Solution:
def addToArrayForm(self, num: List[int], k: int) -> List[int]:
c = 0
ans = []
for i in range(len(num)):
x = k % 10
k = k // 10
n,c = (x + num[len(num)-1-i] + c) % 10,(x + num[len(num)-1-i]+c) // 10
ans = [n]+ans
k = k+c
if k!=0:
while(k!=0):
ans = [k%10] + ans
k = k // 10
return ans
if c == 0:
return ans
else :
return [c]+ans
class Solution:
def addToArrayForm(self, num: List[int], k: int) -> List[int]:
# transform num to an integer
int_num = 0
for digit in num:
int_num = int_num*10 + digit
int_result = int_num + k
result = []
while int_result // 10 > 0:
result.append(int_result % 10)
int_result = int_result// 10
result.append(int_result)
result.reverse()
return result
time complexity: o(N) space complexity: o(N)
1. num array won't be empty, no leading 0's, each digit is valid [0,9]
2. k is non-negative, 1 <= k <= 10^4
3. output most significant -> least significant
4. k can have more digits
carry,
99 + 1 -> 100
98 + 1 -> 99
789 + 12 -> 801
1 + 99 -> 100
go backward from the least significant digit, record carry and current sum digit, update k
check k > 0
check if carry == 1
use a linkedlist and insert into the head
Time: O(number of digits inside num + number of digits inside k)
= O(nums.length + number of digits inside k) = O(max(nums.length, logk))
Space: O(max(nums.length, number of digits inside k) = O(max(nums.length, logk))
class Solution {
public List<Integer> addToArrayForm(int[] num, int k) {
LinkedList<Integer> sum = new LinkedList<>();
int carry = 0, newDigit = 0;
for (int pos = num.length - 1; pos >= 0; pos--) {
newDigit = num[pos] + k % 10 + carry;
carry = newDigit / 10;
newDigit %= 10;
sum.addFirst(newDigit);
k /= 10;
}
while (k > 0) {
newDigit = k % 10 + carry;
carry = newDigit / 10;
newDigit %= 10;
sum.addFirst(newDigit);
k /= 10;
}
if (carry == 1) {
sum.addFirst(1);
}
return sum;
}
}
// 参考题解:https://leetcode-cn.com/problems/add-to-array-form-of-integer/solution/989-ji-zhu-zhe-ge-jia-fa-mo-ban-miao-sha-8y9r/
class Solution {
public:
vector<int> addToArrayForm(vector<int>& num, int k) {
int n = num.size();
vector<int> res;
int sum = 0, carry = 0;
int i = n - 1;
// 从后往前遍历是因为符合加法运算逻辑
while (i >= 0 || k != 0) {
// 对齐计算位数,补0
int x = i >= 0 ? num[i] : 0;
// %10 取个位
int y = k != 0 ? k % 10 : 0;
sum = x + y + carry;
carry = sum / 10;
i--;
k /= 10;
res.push_back(sum % 10);
}
// 计算最后一位的时候,可能有进位问题,有进位的话补入结果数组
if (carry != 0) res.push_back(carry);
// res数组是倒序的,所以需要反转
reverse(res.begin(), res.end());
return res;
}
};
class Solution {
public:
vector<int> addToArrayForm(vector<int>& num, int k) {
reverse(num.begin(), num.end());
vector<int> num2 = splitToArray(k);
num = addTwoArrays(num, num2);
reverse(num.begin(), num.end());
return num;
}
private:
vector<int> splitToArray(int k) {
if (k < 0 || k > 10000) {
cout << "invalid input" << endl;
return {};
}
vector<int> res = {};
while (k) {
res.push_back(k % 10);
k /= 10;
}
return res;
}
vector<int> addTwoArrays(vector<int>num1, vector<int>num2) {
int sz1 = num1.size();
int sz2 = num2.size();
int n = 0;
int carry = 0;
while (n < sz1 && n < sz2) {
int sum = num1[n] + num2[n] + carry;
carry = sum / 10;
num1[n++] = sum % 10;
}
while (n < sz1) {
int sum = num1[n] + carry;
carry = sum / 10;
num1[n++] = sum % 10;
}
while (n < sz2) {
int sum = num2[n++] + carry;
carry = sum / 10;
num1.push_back(sum % 10);
}
if (carry) {
num1.push_back(carry);
}
return num1;
}
};
时间 O(n) 空间 O(1)
数字转化成数组,按位相加,注意进位
func reverse(num []int) {
for i, j := 0, len(num)-1; i < j; {
num[i], num[j] = num[j], num[i]
i++
j--
}
}
func addToArrayForm(num []int, k int) []int {
if k == 0 {
return num
}
k_list := make([]int, 5)
for i:=0;k != 0;i++{
k_list[i] = k%10
k/=10
}
max_length := int(math.Max(float64(len(num)), float64(len(k_list)))) + 1
ans := make([]int, max_length)
reverse(num)
for i := 0; i < max_length; i++ {
num_num := 0
k_num := 0
ans_num := ans[i]
if i < len(num) {
num_num = num[i]
}
if i < len(k_list) {
k_num = k_list[i]
}
data := num_num + k_num + ans_num
if data >= 10 {
ans[i+1] += 1
}
ans[i] = data % 10
}
reverse(ans)
i := 0
for ans[i] == 0 {
i++
}
return ans[i:]
}
时间:O(n) 空间:O(n)
https://leetcode-cn.com/problems/add-to-array-form-of-integer/
对于非负整数 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
-多次利用三元运算符来判断决定变量的值,进位算是难点
Java Code:
class Solution {
public List<Integer> addToArrayForm(int[] num, int k) {
int carry = 0;
List<Integer> result = new LinkedList<>();
int i = num.length-1;
while (k>0 || i>=0){
int x = i <0 ?0:num[i];
int y = k%10;
k = k/10;
int sum = x+y+carry >=10 ? x+y+carry-10:x+y+carry;
result.add(sum);
carry = x+y+carry >= 10 ? 1:0;
i--;
}
if(carry == 1){
result.add(carry);
}
Collections.reverse(result);
return result;
}
}
复杂度分析
令 n 为数组长度。
989. 数组形式的整数加法
入选理由
暂无
题目地址
https://leetcode-cn.com/problems/add-to-array-form-of-integer/
前置知识
题目描述
给定非负整数 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