Add to Array-Form of Integer - Leetcode 989 - Python

preview_player
Показать описание

Solving Add to Array-Form of Integer - Leetcode 989, today's daily leetcode problem.

0:00 - Read the problem
1:02 - Drawing Explanation
9:00 - Coding Explanation

leetcode 989

#neetcode #leetcode #python
Рекомендации по теме
Комментарии
Автор

I was stuck on this one and couldn't understand the solutions either. This video showed me the way. Thank you so much

titajohn
Автор

Complexity is not O(number of digits in K), you reversed array so its O(n), n is size of num.

litheshshetty
Автор

what's tool's name that you use to draw on the screen?

AhmedMohamed-eszo
Автор

Wouldnt reversing be an O(n) operation every time?

MeMe-twxb
Автор

By using pointers we don't need to reverse twice,

carry = 0
res = []
i = len(num)-1
for n in range(max(len(num), len(str(k)))):
digit1 = num[i] if i>= 0 else 0
digit2 = k%10 if k else 0
sum = digit1+digit2+carry
carry = sum//10
sum = sum%10 if sum>=10 else sum
res.append(sum)
i -= 1
k = k//10 if k else 0

if carry:
res.append(carry)
return res[::-1]

techwithkiran
Автор

Why reverse the number though, oh its for cases when k>numbers in array

vidhya
Автор

class Solution {
public List<Integer> addToArrayForm(int[] num, int k) {
List<Integer> list = new ArrayList<>();
int carry = 0;

for (int i = num.length - 1; i >= 0 || k > 0 || carry > 0; i--) {
int x = (i >= 0) ? num[i] : 0;
int sum = x + k % 10 + carry;
list.add(sum % 10);
carry = sum / 10;
k /= 10;
}

Collections.reverse(list);
return list;
}
}

user.-mnix
Автор

This is not supposed to be EASY level :(

souvikmukherjee
Автор

270 ms code beats more than 95% submissions ?

democreation
welcome to shbcf.ru