|
| 1 | +""" |
| 2 | +338. Counting Bits |
| 3 | +https://leetcode.com/problems/counting-bits/description/ |
| 4 | +
|
| 5 | +Solution 1: |
| 6 | + - Convert the number to binary string |
| 7 | + - Sum the number of 1s in the binary string |
| 8 | + - Append the sum to the output list |
| 9 | + - Return the output list |
| 10 | +
|
| 11 | +Time complexity: O(nlogn) |
| 12 | + - The for loop runs n times |
| 13 | + - The sum function runs O(logn) times |
| 14 | +
|
| 15 | +Space complexity: O(n) |
| 16 | + - The output list has n elements |
| 17 | + |
| 18 | +class Solution: |
| 19 | + def countBits(self, n: int) -> List[int]: |
| 20 | + output = [] |
| 21 | + for i in range(n + 1): |
| 22 | + _str = str(bin(i))[2:] |
| 23 | + _sum = sum(map(int, _str.strip())) |
| 24 | + output.append(_sum) |
| 25 | +
|
| 26 | + return output |
| 27 | +""" |
| 28 | + |
| 29 | +""" |
| 30 | +Solution 2 |
| 31 | + We can solve this problem with dynamic programming. |
| 32 | + 1. Initialize output with n elements |
| 33 | + 2. The first element is 0 because iteration starts from zero. |
| 34 | + 3. Iterate from 1 to n+1 |
| 35 | + 4. The last digit of each number is 0 for even number 1 for odd number |
| 36 | + So add (i & 1) to the output |
| 37 | + 5. The digits except the last one can be found when the number is divided by two. |
| 38 | + Instead for division by two, we can use one step of bit shift to the right. |
| 39 | +
|
| 40 | + 0 = 00000 |
| 41 | + 1 = 00001 |
| 42 | + 2 = 00010 |
| 43 | + 3 = 00011 |
| 44 | + 4 = 00100 |
| 45 | + 5 = 00101 |
| 46 | + 6 = 00110 |
| 47 | + 7 = 00111 |
| 48 | +
|
| 49 | +Time complexity: O(n) |
| 50 | + - The for loop runs n times |
| 51 | +
|
| 52 | +Space complexity: O(n) |
| 53 | + - The output list has n elements |
| 54 | +""" |
| 55 | + |
| 56 | +from typing import List |
| 57 | + |
| 58 | +class Solution: |
| 59 | + def countBits(self, n: int) -> List[int]: |
| 60 | + output = [0] * (n+1) |
| 61 | + |
| 62 | + for i in range(1, n+1): |
| 63 | + output[i] = output[i >> 1] + (i & 1) |
| 64 | + |
| 65 | + return output |
0 commit comments