All problems
0388EasyDivide and ConquerBit Manipulation

Energised Relay Count

Tracked in this browser only
Write code

Trains the technique from

LeetCode 191Number of 1 Bits

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

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 is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def hamming_weight(state: int) -> int:
Java
public int hammingWeight(int state)
September 7
Apply