1.第一题:
使用dict来标记字符的对应情况再来判断,代码如下:
class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
mapping=dict()
used=set()
for i ,char in enumerate(s):
if char not in mapping and t[i] not in used:
mapping[char]=t[i]
used.add(t[i])
elif char not in mapping or mapping[char]!=t[i]:
return False
return True
2.第二题:
class Solution:
def addDigits(self, num: int) -> int:
def cal(n):
res=0
while n:
res+=n%10
n=n//10
return res
key=0
while num>=10:
num=cal(num)
return num
3.第三题:
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
s=0
i=0
while i<len(nums):
if nums[i]==0:
s+=1
nums.remove(nums[i])
else:
i+=1
for j in range(s):
nums.append(0)
4.第四题:
这道题使用二进制与的方式来计算两数相加
class Solution:
def getSum(self, a: int, b: int) -> int:
MASK=0x100000000
MAX_INT=0x7FFFFFFF
MIN_INT=MAX_INT+1
while b!=0:
#计算进位
carry=(a&b)<<1
#取余范围限制在[0,2^32-1]
a=(a^b)%MASK
b=carry%MASK
return a if a<=MAX_INT else ~((a%MIN_INT)^MAX_INT)