15% off all plans & roadmaps Use code
See plansLeetCode 191 · Solution & editorial
Given a positive integer n, write a function that returns the number of set bits in its binary representation (also known as the Hamming weight).
Number of 1 Bits is a Bit Manipulation Patterns problem, in the Bitwise AND - Counting Set Bits (Hamming Weight) subpattern. The pattern covers XOR tricks, counting bits, power-of-two checks, and Hamming weight
Count number of 1 bits (Hamming weight) using bitwise AND operations.
The reference solution runs in O(1) time and O(1) space.
Number of 1 Bits has been reported in interviews at Box, Cisco, Microsoft, Qualcomm.
The full editorial is part of Pro
It explains the core insight, the complexity analysis and the common mistakes, with a worked solution.
Number of 1 Bits is a Bit Manipulation Patterns problem, in the Bitwise AND - Counting Set Bits (Hamming Weight) subpattern. Once the approach above makes sense, write it yourself and then work through the neighbouring problems that reuse it.