326. Power of Three
Given an integer, write a function to determine if it is a power of three.
给定一个整数,写一个函数来判断它是否是 3 的幂次方。
class Solution(object):
def isPowerOfThree(self, n):
"""
:type n: int
:rtype: bool
"""
if n<1:
return False
while n%3==0:
n/=3
if n==1:
return True
else:
return False
343. Integer Break
Given a positive integer n, break it into the sum of at least two positive integers and maximize the product of those integers. Return the maximum product you can get.
Example 1:
Input: 2 Output: 1 Explanation: 2 = 1 + 1, 1 × 1 = 1.
Example 2:
Input: 10 Output: 36 Explanation: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36.
给定一个正整数 n,将其拆分为至少两个正整数的和,并使这些整数的乘积最大化。 返回你可以获得的最大乘积。
class Solution(object):
def integerBreak(self, n):
"""
:type n: int
:rtype: int
"""
if n==2:
return 1
if n==3:
return 2
res=1
while n>4:
res*=3
n-=3
return res*n
357. Count Numbers with Unique Digits
Example:
Input: 2
Output: 91
Explanation: The answer should be the total numbers in the range of 0 ≤ x < 100,
excluding 11,22,33,44,55,66,77,88,99
思路:
- 如果n = 1,那么可以有10个数字不同(0~9)
- 如果n >= 2,那么第一位可以是1~9共9个数字,第二位可以是出去第一位的数字+0共9个数字,之后的每位数字都必须不能使用前面已经用过的数字所以依次递减。即9,9,8,7,…,1
- n位数字中由不同的数字构成的数字,是比它小的各位数字所能构成的该条件的数字求和。
class Solution(object):
def countNumbersWithUniqueDigits(self, n):
"""
:type n: int
:rtype: int
"""
nums=[9,9,8,7,6,5,4,3,2,1]
ans,m=1,1
for i in range(min(n,10)):
m*=nums[i]
ans+=m
return ans
367. Valid Perfect Square
Given a positive integer num, write a function which returns True if num is a perfect square else False.
Note: Do not use any built-in library function such as sqrt
.
Example 1:
Input: 16 Output: true
Example 2:
Input: 14 Output: false
给定一个正整数 num,编写一个函数,如果 num 是一个完全平方数,则返回 True,否则返回 False。
class Solution(object):
def isPerfectSquare(self, num):
"""
:type num: int
:rtype: bool
"""
low=1
high=num
while low<=high:
mid=(low+high)/2
if mid*mid>num:
high=mid-1
elif mid*mid<num:
low=mid+1
else:
return True
return False