leetcode [python] 【338】Counting Bits
思路一:發現數字規律求解:
1: 1
2,3: 1,2
4,5,6,7: 1,2,2,3
class Solution(object):
def countBits(self, num):
"""
:type num: int
:rtype: List[int]
"""
nums = [0]
if num == 0:
return nums
a = int(math.log(num,2))
temp =[1]
for i in range(a):
nums.extend(temp)
temp = temp + [ele+1 for ele in temp]
b = num - int(math.pow(2,a)) + 1
nums.extend(temp[:b])
return nums
思路二:利用奇偶性:
對於一個奇數,二進位制中1的個數等於其折半數的二進位制中1的個數加1
所以只需將一個數除以2,判斷最低位是否為1
所以可以有遞推公式 res[i] = res[i/2] + (i&1),這裡i/2等價於i>>1
class Solution(object):
def countBits(self, num):
"""
:type num: int
:rtype: List[int]
"""
res = [0] * (num + 1)
for i in xrange(1,num + 1):
res[i] = res[i/2] + (i & 1)
return res
思路三:利用最高位:
11(3) = 8(1) + 3(2) 一個數分解為最大2的整數冪和X
class Solution(object):
def countBits(self, num):
"""
:type num: int
:rtype: List[int]
"""
res = [0] * (num + 1)
for i in range(1,num + 1):
res[i] = res[i - (1<<int(math.log(i,2)))] + 1
return res
相關文章
- 【LeetCode】Counting Bits(338)LeetCode
- LeetCode 338 Counting BitsLeetCode
- LeetCode 第 338 題 (Counting Bits)LeetCode
- 338. Counting Bits--LeetCode RecordLeetCode
- LeetCode-Reverse BitsLeetCode
- LeetCode-Count BitsLeetCode
- leetcode刷題--Reverse BitsLeetCode
- leetcode刷題--Number of 1 BitsLeetCode
- leetcode 338 位元位計數LeetCode
- [LeetCode] 191. Number of 1 BitsLeetCode
- LeetCode 第 190 題 (Reverse Bits)LeetCode
- LeetCode 第 191 題 (Number of 1 Bits)LeetCode
- OS kernel Bits 32/64 bits?
- python ref counting based garbage collectionPython
- 338
- Python演算法:Counting 101Python演算法
- GCD CountingGC
- Reversing Bits in C
- 【LeetCode從零單排】No 191.Number of 1 Bits(考察位運算)LeetCode
- [ABC338E] Chords
- CF 338 D GCD Table(CRT)GC
- 計數排序 - Counting Sort排序
- [ABC338E] Chords 題解
- [CareerCup] 5.1 Insert Bits 插入位
- Automatic Reference Counting-SwiftSwift
- 338、分散式高階篇總結分散式
- iOS中的Reference Counting詳解iOS
- UVa 1225 - Digit CountingGit
- Codeforces 954H Path Counting
- 24位PCM取樣資料轉成16位演算法,已實現PCM轉WAV線上工具原始碼支援24bits、16bits、8bits演算法原始碼
- tooling bits 專欄文章索引索引
- [CareerCup] 5.6 Swap Odd and Even Bits 交換奇偶位
- projecteuler---->problem=19----Counting SundaysProject
- Digit Counting uva1225Git
- CF1919E Counting Prefixes
- Natural Computing: DNA, Quantum Bits, and the Future of Smart MachinesMac
- [leetcode]Gas Station @ PythonLeetCodePython
- Oracle 11G OCP 1Z0-053 338Oracle