leetcode263. Ugly Number /67. Add Binary/504. Base 7
阿新 • • 發佈:2018-12-15
題目描述
醜數-質因子只包含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
題目描述
給定兩個二進位制字串,求它們的和(也用二進位制字串表示) [輸入非空且只包含字元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)
題目描述
返回一個整數的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