1:回文数
思路,将数字转换为字符串,利用字符串的方法,将其翻转来达到效果,我喜欢用最简单的方法,
class Solution:
def isPalindrome(self, x: int) -> bool:
s=str(x)
if s[::-1]== s:
return True
else:
return False
s=Solution()
x=123
print(s.isPalindrome(x))
#罗马数字转换
class Solution(object):
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
d = {'I': 1, 'IV': 3, 'V': 5, 'IX': 8, 'X': 10, 'XL': 30, 'L': 50, 'XC': 80, 'C': 100, 'CD': 300, 'D': 500,
'CM': 800, 'M': 1000}
sum =0
for i, n in enumerate(s):
str1=s[max(i-1,0):i+1]
if str1 in d:
sum+=d.get(str1)
else:
sum+=d[n]
return sum
1的个数
def hanmingWeight(n:int):
m=0
#利用bin函数将数字转换为二进制,同时转换为字符串
for i in range(len(bin(n))):
if bin(n)[i]=='1':
m+=1
return m
print(hanmingWeight(78))
#查找字符串中最长的个数
先根据长度排序,找出最短的字符串,
再进行循环对比
def longesCommonPrefix(strs):
strs=sorted(strs,key=len)
str1=strs[0]
for i in range(len(str1)):
result=str1[0:i+1]
j=0
for j in range(len(strs)):
if (strs[j][0:i+1]!=result):
return str1[0:i]
return result
strs=["abc",'abd','abe']
print(longesCommonPrefix(strs))
一种更加简单的解法,直接让最短的和最长的比较
def longestCommonPrefix(strs):
if not strs:
return ""
s1 = min(strs)
s2 = max(strs)
for i, x in enumerate(s1):
if x != s2[i]:
return s2[:i]
return s1
print(type(longestCommonPrefix(strs)))
#杨辉三角用二维数组解决
class Solution:
def generate(self, numRows: int) -> List[List[int]]:
ret=list()
for i in range(numRows):
row=list()
for j in range(0,i+1):
if j==0 or j==i:
row.append(1)
else:
row.append(ret[i-1][j]+ret[i-1][j-1])
ret.append(row)
return ret
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
if target in nums:
return nums.index(target)
else:
nums.append(target)
nums.sort()
return nums.index(target)
加1
def addone(nums):
s=‘’
l=[]
for i in nums:
s+=str(i) 将数字加入到字符串里面去
s=int(s) 转换成为数字
s+=1 加上1
s=str(s) 再转换成为字符串
for i in s:
l.append(int(i))将字符串里面的转回空列表
return l