326、3的幂
给定一个整数,写一个函数来判断它是否是 3 的幂次方。
示例 1:
输入: 27
输出: true
示例 2:
输入: 0
输出: false
示例 3:
输入: 9
输出: true
class Solution(object):
def isPowerOfThree(self, n):
import math
for i in range(n):
if n == math.pow(3,i) :
return True
else:
continue
return False
solution = Solution()
print(solution.isPowerOfThree(81))
class Solution1(object):
def isPowerOfThree(self, n):
"""
:type n: int
:rtype: bool
"""
if n == 1:
return True
elif n % 3 != 0 or n == 0:
return False
else:
return self.isPowerOfThree(n/3)
'''
在整数范围3的19次方是最大的,它除以num余数等于0则说明num是3的幂
'''
class Solution2(object):
def isPowerOfThree(self, n):
"""
:type n: int
:rtype: bool
"""
return n > 0 and 1162261467 % n == 0
345、翻转字符串中的元音字母
编写一个函数,以字符串作为输入,反转该字符串中的元音字母。
示例 1:
输入: “hello”
输出: “holle”
示例 2:
输入: “leetcode”
输出: “leotcede”
class Solution(object):
def reverseVowels(self, s):
a =['a','o','e','u','A','E','O','U']
i = 0
j = len(s)-1
s = list(s)
while i<j:
while s[i] not in a and i < j:
i += 1
while s[j] not in a and i < j :
j -= 1
s[i],s[j] = s[j],s[i] #同时赋值,元素替换
i += 1
j -= 1
return ''.join(s)
solution =Solution()
print(solution.reverseVowels("leetcode"))
#方法二
class Solution1(object):
def reverseVowels(self, s):
a =['a','o','e','u','A','E','O','U']
s = list(s)
b = []
for i,j in enumerate(s):
if j in a:
b.append(i)
k = 0
l = len(b)-1
while k<l:
s[b[k]],s[b[l]] = s[b[l]],s[b[k]]
k += 1
l -= 1
return ''.join(s)
solution = Solution1()
print(solution.reverseVowels("leetcode"))