xxx
to SumFacebook
interviewers like this question and propose it
in four main variations. The choice of algorithm should be based on the
input format:
# LC 067 Add Binary: sum two binary strings.
# V0
# IDEA : STRING + BINARY
class Solution(object):
def addBinary(self, a, b):
= max(len(a), len(b))
_len if len(a) < _len:
= (_len - len(a)) * '0' + a
a if len(b) < _len:
= (_len - len(b)) * '0' + b
b
= 0
plus = ""
result
# INVERSE LOOPING THE a, b
for i in range(len(a))[::-1]:
= int(a[i]) + int(b[i]) + plus
tmp if tmp > 1:
-= 2
tmp = 1
plus else:
= 0
plus
+= str(tmp)
result
if plus == 1:
return '1' + result[::-1] ### NOTE WE NEED TO REVERSE IT!
else:
return result[::-1] ### NOTE WE NEED TO REVERSE IT!
# V0
class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
= ''
res = len(a)-1, len(b)-1, 0
i, j, plus while i>=0 or j>=0 or plus==1:
+= int(a[i]) if i>= 0 else 0
plus += int(b[j]) if j>= 0 else 0
plus = str(plus % 2) + res
res = i-1, j-1, plus//2 # since max of "plus" is 3 in bimary case, so "plus//2" works here
i, j, plus return res
// java
// LC 415
// V0
// IDEA: string op (fixed by gpt)
public String addStrings(String num1, String num2) {
if (num1 == null || num2 == null) {
if (num1 == null) {
return num2;
}
return num1;
}
if (num1.equals("0") && num2.equals("0")) {
return "0";
}
StringBuilder sb = new StringBuilder();
int plus = 0;
int idx_1 = num1.length() - 1;
int idx_2 = num2.length() - 1;
/** NOTE !!!
*
* 1. while loop
* 2. idx_1 >= 0 or idx_2 >= 0
*/
while (idx_1 >= 0 || idx_2 >= 0) {
int v1 = 0;
int v2 = 0;
int new_val = 0;
/** NOTE !!!
*
* if idx_1 >= 0, then get val from it
*/
if (idx_1 >= 0) {
= Integer.parseInt(String.valueOf(num1.charAt(idx_1)));
v1 -= 1;
idx_1 }
/** NOTE !!!
*
* if idx_1 >= 0, then get val from it
*/
if (idx_2 >= 0) {
= Integer.parseInt(String.valueOf(num2.charAt(idx_2)));
v2 -= 1;
idx_2 }
= (new_val + v1 + v2 + plus);
new_val
/** NOTE !!!
*
* if new_vla > 9,
* we should `subtract 10` (instead of 9)
*/
if (new_val > 9) {
= 1;
plus -= 10;
new_val } else {
= 0;
plus }
.append(new_val);
sb}
/** NOTE !!!
*
* need to add the `remaining plus` to res
* if there is it
*/
if (plus > 0) {
.append(plus);
sb}
// reverse
return sb.reverse().toString();
}
# LC 415. Add Strings
# V0
# IDEA : string + math
class Solution(object):
def addStrings(self, num1, num2):
= []
result # note : we init carry as 0
= 0
carry = list(num1)
num1 = list(num2)
num2 # while there is still non-add digit in num1, and num2; or there is non-zero carry
while num1 or num2 or carry:
= carry
digit if num1:
= num1.pop(-1)
tmp1 += int(tmp1)
digit if num2:
= num2.pop(-1)
tmp2 += int(tmp2)
digit """
if digit > 9 -> we need to "carry" 1 to next digit -> carry = 1
else -> carry = 0
"""
if digit > 9:
= 1
carry else:
= 0
carry # NOTE !!! we get "remain" by 10 via below code
str(digit % 10))
result.append(return ''.join(result[::-1])
# LC 371 : Sum of Two Integers
# V0
# https://leetcode.com/problems/sum-of-two-integers/discuss/1214257/Python-1-line%3A-91-faster
class Souluton:
def getSum(self, a, b):
= math.exp(a) * math.exp(b)
tmp = int(math.log(tmp))
r return r
# LC 989 Add to Array Form of Integer
# V0
# IDEA : array op
class Solution:
def addToArrayForm(self, num, k):
= ""
s for i in num:
+= str(i)
s = int(s) + k
answer return list("".join(str(answer)))
# LC 66 Plus One
# V0
# NOTE : Notice the index of inverse loop : range(len(a)-1, -1, -1)
# a = ['a', 'b', 'c']
# for i in range(len(a)-1, -1, -1):
# print (a[i])
# c
# b
# a
class Solution(object):
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
= 1
plus for i in range(len(digits)-1, -1, -1):
if digits[i] + plus > 9:
= 0
digits[i] = 1
plus else:
= digits[i] + plus
digits[i] = 0
plus if plus == 1:
0, 1)
digits.insert(return digits
# LC 002 Add Two Numbers
# V0
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
NOTE :
1. we init linkedlist via ListNode()
2. we NEED make extra head refer same linkedlist, since we need to return beginning of linkedlust of this func, while res will meet "tail" at the end of while loop
"""
= res = ListNode()
head = 0
plus = 0
tmp while l1 or l2:
+= plus
tmp = 0
plus if l1:
+= l1.val
tmp = l1.next
l1 if l2:
+= l2.val
tmp = l2.next
l2 if tmp > 9:
-= 10
tmp = 1
plus
next = ListNode(tmp)
res.= res.next
res = 0
tmp ### NOTE : need to deal with case : l1, l2 are completed, but still "remaining" plus
if plus != 0:
next = ListNode(plus)
res.= res.next
res #print ("res = " + str(res))
#print ("head = " + str(head))
return head.next
# LC 445 Add Two Numbers II
# V0
# IDEA : string + linked list
# DEMO
# input :
# [7,2,4,3]
# [5,6,4]
# intermedia output :
# l1_num = 7243
# l2_num = 564
class Solution:
def addTwoNumbers(self, l1, l2):
if not l1 and not l2:
return None
= 0
l1_num while l1:
= l1_num * 10 + l1.val
l1_num = l1.next
l1
= 0
l2_num while l2:
= l2_num * 10 + l2.val
l2_num = l2.next
l2
print ("l1_num = " + str(l1_num))
print ("l2_num = " + str(l2_num))
### NOTE : trick here :
# -> get int format of 2 linked list first (l1, l2)
# -> then sum them (l1_num + l2_num)
= l1_num + l2_num
lsum
= ListNode(None)
head = head
cur ### NOTE : go thrpigh the linked list int sum, append each digit to ListNode and return it
for istr in str(lsum):
next = ListNode(int(istr))
cur.= cur.next
cur # NOTE : need to return head (but not cur, since cur already meet the end of ListNode)
return head.next