版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/a786150017/article/details/83063054
263. Ugly Number
题目描述
丑数-质因子只包含2, 3, 5的正数。输入一个数, 判断它是不是丑数
例子
Example 1:
Input: 6
Output: true
Explanation: 6 = 2 × 3
Example 2:
Input: 8
Output: true
Explanation: 8 = 2 × 2 × 2
Example 3:
Input: 14
Output: false
Explanation: 14 is not ugly since it includes another prime factor 7.
解法
注意 - num小于等于0的情况
时间复杂度 - n是2的幂次方时,此时时间复杂度为O(logn)
代码
class Solution(object):
def isUgly(self, num):
"""
:type num: int
:rtype: bool
"""
if num <= 0:
return False
for i in [2,3,5]:
while num % i == 0:
num //= i
return num == 1
67. Add Binary
题目描述
给定两个二进制字符串,求它们的和(也用二进制字符串表示)
[输入非空且只包含字符1/0]
例子
Example 1:
Input: a = “11”, b = “1”
Output: “100”
Example 2:
Input: a = “1010”, b = “1011”
Output: “10101”
解法
法1 - python特性 int(x, base = 2)
法2 - 这题的本意应该是模拟二进制加法
解法1
用内置函数int
class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
return bin(int(a, 2) + int(b, 2))[2:]
解法2
模拟二进制加法
class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
a, b = int(a), int(b)
summ = carry = 0
base = 1
while a or b or carry:
temp = carry + a % 10 + b % 10
if temp > 1: # 当前求和结果为2或3, 此时需要进位
temp = temp % 2
carry = 1
else:
carry = 0
summ += temp * base
a //= 10
b //= 10
base *= 10
return str(summ)
504. Base 7
题目描述
返回一个整数的7进制表示
例子
Example 1:
Input: 100
Output: “202”
Example 2:
Input: -7
Output: “-10”
解法
考虑熟悉的10进制转2进制,一直除以2,直到为0
把每次得到的余数逆序拼接√ — 7进制同理
<注意> 对负数先标记符号 / 特殊情况- num为0
代码
class Solution(object):
def convertToBase7(self, num):
"""
:type num: int
:rtype: str
"""
if num == 0:
return '0'
Flag = ''
if num < 0:
num = -num
Flag = '-'
ss = ''
while num:
ss = str(num % 7) + ss
num //= 7
return Flag + ss