【leecode刷题】初级算法-数学

tech2024-12-15  8

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 """ # def isPrimeNum(num): # for i in range(2,num): # if num%i==0: # return False # return True # if n==0 or n==1: # return 0 # else: # count = 0 # for i in range(2,n): # if isPrimeNum(i): # count = count+1 # return count if n < 2: return 0 isPrime = [1] * n isPrime[0] = isPrime[1] = 0 # 0和1不是质数,先排除掉 # 埃式筛,把不大于根号n的所有质数的倍数剔除 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 """ # 循环解法 # if n<1: # return False # flag = True # while n>1 and flag: # if n%3==0: # n = n//3 # else: # flag = False # return flag 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
最新回复(0)