leetcode-338. 比特位計數
阿新 • • 發佈:2018-08-19
進制數 def sel append 數字 函數 輸入 tco range
給定一個非負整數 num。對於 0 ≤ i ≤ num 範圍中的每個數字 i ,計算其二進制數中的 1 的數目並將它們作為數組返回。
示例 1:
輸入: 2
輸出: [0,1,1]
示例 2:
輸入: 5
輸出: [0,1,1,2,1,2]
進階:
- 給出時間復雜度為O(n*sizeof(integer))的解答非常容易。但你可以在線性時間O(n)內用一趟掃描做到嗎?
- 要求算法的空間復雜度為O(n)。
- 你能進一步完善解法嗎?要求在C++或任何其他語言中不使用任何內置函數(如 C++ 中的 __builtin_popcount)來執行此操作。
思路:
1. 很容易可以想到依次遍歷,計算每個數字的二進制數中的1的數目。
2. 觀察數字二進制位中‘1’的特征:
0 000
1 001
2 010
3 011
4 100
5 101
6 110
可以發現數字n的二進制位中1的個數為數字 n>>1 加上二進制末位是否為1,可以根據這個特征來計算。
代碼:
class Solution: def countBits(self, num): """ :type num: int :rtype: List[int] """ res = [0]for i in range(1, num + 1): res.append(res[i >> 1] + i % 2) return res if __name__ == ‘__main__‘: s = Solution() print(s.countBits(2)) print(s.countBits(5))
leetcode-338. 比特位計數