记录有意思的算法题, 大都不是自己写的,学习一下 >_<
字符串
1 LC415 字符串相加
class Solution(object):
def addStrings(self, num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
res = ""
i, j = len(num1) - 1, len(num2) - 1
carry = 0 #进位
while i >= 0 or j >= 0:
if i < 0:
n1 = 0
else:
n1 = int(num1[i])
if j < 0:
n2 = 0
else:
n2 = int(num2[j])
tmp = n1 + n2 + carry
carry = tmp // 10
res = str(tmp % 10) + res
i -= 1
j -= 1
return "1" + res if carry else res
2 36进制加法
和上题代码一样。
def getInt(x):
if '0' <= x <= '9':
x_int = int(x)
else:
x_int = ord(x) - ord('a') + 10
return x_int
def getChar(x):
if x <= 9:
x_char = str(x)
else:
x_char = chr(x - 10 + ord('a'))
return x_char
def addStrings(num1, num2):
res = ""
i, j = len(num1) - 1, len(num2) - 1
carry = 0 #进位
while i >= 0 or j >= 0:
if i < 0:
n1 = 0
else:
n1 = getInt(num1[i])
if j < 0:
n2 = 0
else:
n2 = getInt(num2[j])
tmp = n1 + n2 + carry
carry = tmp // 36
res = getChar(tmp % 36) + res
i -= 1
j -= 1
return "1" + res if carry else res
print(addStrings("1b" , "2x"))