Classic problem #191EasyDivide and ConquerBit Manipulation
Number of 1 Bits
Real-world version: Energised Relay CountTracked in this browser only
Read Number of 1 Bits on LeetCode(opens in a new tab)
The statement here is our own: the same inputs, outputs and technique.
A test rig drives a bank of relays from one control register. The register holds the positive integer state, and relay k is energised exactly when the bit of weight 2^k is set in state.
Return how many relays are energised.
Examples
Example 1
- Input
- state = 26
- Output
- 3
26 is 11010 in binary, and three of those bits are set.
Example 2
- Input
- state = 512
- Output
- 1
512 is 2^9, so only the relay of weight 512 is energised.
Example 3
- Input
- state = 4095
- Output
- 12
4095 is 111111111111 in binary, twelve set bits in a row.
Example 4
- Input
- state = 1073741824
- Output
- 1
1073741824 is 2^30, so a single relay near the top of the bank is energised.
Constraints
- 1 <= state <= 2^31 - 1
The signature
The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
Python
def hamming_weight(state: int) -> int:Java
public int hammingWeight(int state)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 11 test cases: 11 passed
- Passed: 4 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's