1、Fizz Buzz
class Solution(object):
def fizzBuzz(self
, n
):
"""
:type n: int
:rtype: List[str]
"""
result
= []
for i
in range(1,n
+1):
if i
%3 == 0 and i
%5 == 0:
result
.append
("FizzBuzz")
elif i
%3 == 0:
result
.append
("Fizz")
elif i
%5 == 0:
result
.append
("Buzz")
else:
result
.append
(str(i
))
return result
2、计数质数
class Solution(object):
def countPrimes(self
, n
):
"""
:type n: int
:rtype: int
"""
if n
< 2:
return 0
isPrime
= [1] * n
isPrime
[0] = isPrime
[1] = 0
for i
in range(2, int(n
** 0.5) + 1):
if isPrime
[i
]:
isPrime
[i
* i
:n
:i
] = [0] * ((n
- 1 - i
* i
) // i
+ 1)
return sum(isPrime
)
3、3的幂
class Solution(object):
def isPowerOfThree(self
, n
):
"""
:type n: int
:rtype: bool
"""
def isPowerOfThree1(n
):
if n
<=0:
return 0
elif n
==1 :
return 1
else:
return isPowerOfThree1
(n
//3)*(not n
%3)
return isPowerOfThree1
(n
)
4、罗马数字转整数
class Solution(object):
def romanToInt(self
, s
):
"""
:type s: str
:rtype: int
"""
specialCharSet
= {"IV":4,"IX":9,"XL":40,"XC":90,"CD":400,"CM":900}
charSet
= {"I":1,"V":5,"X":10,"L":50,"C":100,"D":500,"M":1000}
value
= 0
i
= 0
while i
< len(s
):
firstChar
= s
[i
]
if i
==len(s
)-1:
secondChar
=""
else:
secondChar
=s
[i
+1]
char
= firstChar
+secondChar
if char
in specialCharSet
:
value
= value
+ specialCharSet
[char
]
i
= i
+2
else:
value
= value
+ charSet
[firstChar
]
i
= i
+1
return value
转载请注明原文地址:https://tech.qufami.com/read-19666.html