435. Counting Bits
Given an integer n, return an array ans of length n +1 such that for each i (0 <= i <=n), ans[i] is the number of 1's in the binary representation of i.
1. Problem Understanding
The problem asks us to count the number of 1s (set bits) in the binary representation of every integer from 0 to n. The result should be returned as an array where the value at index i represents the count of set bits in the binary representation of i.
2. Core Concepts
' Binary Representation:
- Binary is a base-2 number system where each digit represents a power of 2.
' Key Observations
- Any number i can be broken down as:
- i >> 1: This is the number i divided by 2 (dropping the least significant bit)
- i & 1 : This checks whether the least significant bit (LSB) of i or 1 or 0.
' Dynamic Programming Insight
- Using the above formula, we can compute the number of set bits for i by reusing the results we computed for smaller numbers. This is an example of a bottom-up dynamic programming approach.
3. Key Bitwise Operations
' Right Shift (>>)
- Shifts the bits of a number to the right, effectively dividing the number by 2
' Bitwise And (&):
- Compares each bit of two number and returns 1 if both bits are 1
- Check if a number is odd or even
' Bitwise OR(|) and XOR(^)
- OR: Returns 1 if at least one bit is 1
- XOR: Returns 1 if the bits are different
class Solution:
def countBits(self, n: int) -> List[int]:
ans = [0] * (n+1)
for i in range(1, len(ans)):
ans[i] = ans[i >> 1] + (i & 1)
return ans
'개발 공부 > Algorithm' 카테고리의 다른 글
[LeetCode] 17. Letter Combinations of a Phone Number (2) | 2024.12.13 |
---|---|
[LeetCode] 2390. Removing Stars From a String (0) | 2024.12.10 |
[LeetCode] 435. Non-overlapping Intervals (0) | 2024.12.08 |
it 취업을 위한 알고리즘 문제풀이 - 1. 코드 구현력 기르기 (0) | 2020.09.16 |
알고리즘 문제 해결 전략 Part02. 알고리즘 분석 (0) | 2020.07.09 |