1.Add Binary
class Solution:
def addBinary(self, a: str, b: str) -> str:
max_len = max(len(a),len(b))
a = a.rjust(max_len,'0')
b = b.rjust(max_len,'0')
in_flag = 0
s = ''
for i in range(max_len):
p = max_len-1-i
in_flag,num = divmod( int(a[p])+int(b[p])+in_flag,2)
s = str(num)+s
if in_flag>0:
s = str(in_flag)+s
return s
class Solution:
def addBinary(self, a: str, b: str) -> str:
return bin(eval('0b'+a)+eval('0b'+b))[2:]
2.Add to Array-Form of Integer
class Solution:
def addToArrayForm(self, A: List[int], K: int) -> List[int]:
for i in range(len(A)-1,-1,-1):
K, A[i] = divmod(A[i]+K,10)
if K>0:
K = [int(i) for i in str(K)]
K.extend(A)
return K
else:
return A
3. Add Strings
class Solution:
def addStrings(self, num1: str, num2: str) -> str:
max_len = max(len(num1),len(num2))
num1 = num1.rjust(max_len,'0')
num2 = num2.rjust(max_len,'0')
s = ''
carry = 0
for i in range(max_len-1,-1,-1):
carry,num = divmod(int(num1[i])+int(num2[i])+carry,10)
s = str(num)+s
if carry>0:
s = str(carry)+s
return s
4. Add Two Numbers
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
res_node = ListNode(0)
p = res_node
carry = 0
while l1 or l2 or carry:
v1=v2=val=0
if l1:
v1=l1.val
l1=l1.next
if l2:
v2=l2.val
l2=l2.next
carry,val = divmod(v1+v2+carry,10)
p.next = ListNode(val)
p=p.next
return res_node.next
5. Add Two Numbers II
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
'''
1.用栈的方法
'''
s1 = []
s2 = []
head = ListNode(0)
while l1:
s1.append(l1.val)
l1 = l1.next
while l2:
s2.append(l2.val)
l2 = l2.next
carry = 0
res_node = ListNode(0)
p = res_node
while s1 or s2 or carry:
v1=v2=val=0
if s1:
v1 = s1.pop()
if s2:
v2 = s2.pop()
carry,val = divmod(v1+v2+carry,10)
head.val = val
tmp = head
head = ListNode(0)
head.next = tmp
return head.next
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
'''
2.直接用数字加和
'''
num1 = 0
while l1:
num1 = num1*(10)+l1.val
l1 = l1.next
num2 = 0
while l2:
num2 = num2*(10)+l2.val
l2 = l2.next
num = num1+num2
head = ListNode(0)
p = head
s = str(num)
for i in range(len(s)):
node = ListNode(int(s[i]))
p.next=node
p = p.next
return head.next