Problem 191

Abstract / Summary

Count how many 1 bits are in the binary representation of a given number.

Note

The full problem description, including helpful examples, can be found on LeetCode.

C++ 0191.cpp

class Solution {
public:
    int hammingWeight(uint32_t n) {
        int result = 0;
        while (n > 0)
        {
            result++;
            n &= n - 1;
        }
        return result;
    }
};
12 lines | 217 bytes | submitted August 9, 2023 | GitHub   tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 77% (2+ million submissions).

Typical patterns to solve this problem:
  • Bit Manipulation
  • Divide And Conquer
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a class Solution with a single public member function hammingWeight. The function receives a 32-bit unsigned integer and returns the count of bits set to 1 in its binary representation. The algorithm iteratively clears the least-significant set bit until the value becomes zero, incrementing a counter on each iteration. This approach yields the exact Hamming weight of the input value.

Key Steps

The core logic is expressed in a loop that runs while the input n is non-zero. The first statement inside the loop increments the result counter, reflecting the discovery of a set bit. The second statement applies the expression n &= n - 1, which removes the lowest set bit from n. After the loop terminates, the accumulated count is returned.

int result = 0;
while (n > 0)
{
    result++;
    n &= n - 1;
}
return result;

The initialization of result to zero establishes the starting count. The loop condition n > 0 guarantees that the body executes only when there remains at least one set bit. The increment operation result++ records the removal of a set bit. The bitwise operation n &= n - 1 is the pivotal step that transforms n by clearing its least-significant 1. Finally, the function returns the total number of cleared bits, which equals the Hamming weight.

Edge Cases

When the input value n is zero, the loop condition fails immediately, and the function returns the initial value of result, which is zero. This correctly represents the fact that a zero value contains no set bits. For the maximum possible 32-bit unsigned integer (0xFFFFFFFF), the loop iterates exactly 32 times, each iteration clearing one bit, and the final result is 32. The algorithm therefore handles both the lower bound (no bits set) and the upper bound (all bits set) without special-case code.

Performance Optimizations

The use of n &= n - 1 is a classic bit-twiddling technique that reduces the number of loop iterations to the number of set bits rather than the total number of bits in the word. Consequently, the runtime scales with the sparsity of the input: inputs with few 1s complete quickly, while dense inputs require more iterations but never exceed 32 cycles for a 32-bit integer. This eliminates the need for a fixed-size iteration over each bit position and avoids unnecessary conditional checks for each bit. The algorithm also operates entirely with registers and simple arithmetic, ensuring minimal overhead.

written by openai gpt

ELI5 - Simplified Explanation

Imagine that every number is made up of a long row of tiny light bulbs that are either turned on or turned off. Computers see numbers as these rows of lights. A light that is on is like the number one, and a light that is off is like the number zero.

This piece of code is on a treasure hunt to find out how many light bulbs are glowing brightly. It starts with a little counter set to zero. Then, it looks at the row of bulbs. Whenever it finds a bulb that is shining, it adds one to the counter.

To do this very quickly, the code uses a special trick. Every time it finds a light that is on, it magically turns that light off and moves on to find the next one. It keeps doing this over and over again until all the bulbs are dark. Once there are no more glowing lights left to find, the counter shows exactly how many lights were shining at the very beginning.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 9 | μ = 8.88 | σ = 0.70

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java C JS Go Rust TS
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github begeekmyfriend C
BigEggStudy C#
black-shadows C++
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
Dijkstra-Edu Java
everthis JS
fartem Ruby
fengvyi C++
fpdjsns C++
gaosq0604 Python
Garvit244 Python
halfrost Go
haoel C++
JoshCrozier JS
keineahnung2345 C++
Krazune C++
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
muhammadfarhankt Go
qiyuangong Python
shreymehul C#
sonugiri1043 C++
suxrobGM C#
varunu28 Java
vli02 C
vthwang Java
XiaotaoGuo C++
yuanliu666 Kotlin
YuriSpiridonov Python
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C, C++, Go, Java, JavaScript, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
begeekmyfriend C
BigEggStudy C#
black-shadows C++, C++
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
Dijkstra-Edu Java
everthis JavaScript
fartem Ruby
fengvyi C++
fpdjsns C++
gaosq0604 Python
Garvit244 Python
halfrost Go
haoel C++
JoshCrozier JavaScript
keineahnung2345 C++
Krazune C++
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
muhammadfarhankt Go
qiyuangong Python
shreymehul C#
sonugiri1043 C++
suxrobGM C#
varunu28 Java
vli02 C
vthwang Java
XiaotaoGuo C++
yuanliu666 Kotlin
YuriSpiridonov Python
zfang399 C++
57 links | 40 authors | 11 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Number of 1 Bits | Live Coding with Explanation | Leetcode - 191'
Algorithms Made Easy 8 mins
Number of 1 Bits | Live Coding with Explanation | Leetcode - 191
YouTube video 'Number of 1 Bits - Leetcode 191 - Bit Manipulation (Python)'
Greg Hogg 5 mins
Number of 1 Bits - Leetcode 191 - Bit Manipulation (Python)
YouTube video 'Number of 1 Bits | 4 Approaches | Time Complexity | Apple | Microsoft | Amazon | Leetcode 191'
codestorywithMIK 19 mins
Number of 1 Bits | 4 Approaches | Time Complexity | Apple | Microsoft | Amazon | Leetcode 191
YouTube video '191. Number of 1 Bits | 2 Ways | O(No of Set Bits)'
Aryan Mittal 11 mins
191. Number of 1 Bits | 2 Ways | O(No of Set Bits)
YouTube video 'Number of 1 Bits - LeetCode 191 - JavaScript'
AlgoJS 4 mins
Number of 1 Bits - LeetCode 191 - JavaScript
YouTube video 'Number of 1 bits | Leetcode 191 | No of 1 bits'
Coding Decoded 10 mins
Number of 1 bits | Leetcode 191 | No of 1 bits
YouTube video 'Number of 1 Bits - LeetCode 191 - Python'
Deepti Talesra 12 mins
Number of 1 Bits - LeetCode 191 - Python
YouTube video '✅  Number of 1 Bits  - Simple Interview Solution - LeetCode 191 - Visualized Too'
Leet Logics 6 mins
✅ Number of 1 Bits - Simple Interview Solution - LeetCode 191 - Visualized Too
YouTube video '191. Number of 1 Bits | LEETCODE EASY | BITS MANIPULATION'
code Explainer 8 mins
191. Number of 1 Bits | LEETCODE EASY | BITS MANIPULATION
YouTube video 'Number of 1 Bits | Leetcode 191 | Bit Manipulation 🔥🔥🔥 | Live coding session'
Coding Decoded 3 mins
Number of 1 Bits | Leetcode 191 | Bit Manipulation 🔥🔥🔥 | Live coding session
YouTube video 'LeetCode 191: Number of 1 Bits | 4 Easy Python Solutions | Bitwise Tricks | srkcodes'
Srk Codes 15 mins
LeetCode 191: Number of 1 Bits | 4 Easy Python Solutions | Bitwise Tricks | srkcodes
YouTube video '191. Number of 1 bits | Leetcode | Bit Manipulation | Fundamentals'
Coding with Tamilarasan 7 mins
191. Number of 1 bits | Leetcode | Bit Manipulation | Fundamentals
YouTube video '191. Number of 1 bits | Bit Manipulation | Amazon | Apple | Easy Explanation | Leetcode'
Rapid Syntax 7 mins
191. Number of 1 bits | Bit Manipulation | Amazon | Apple | Easy Explanation | Leetcode
YouTube video 'Daily Leetcode #786: May 26, 2022 - 191. Number of 1 Bits'
Programming Live with Larry 4 mins
Daily Leetcode #786: May 26, 2022 - 191. Number of 1 Bits
YouTube video 'Number of 1 Bits - Leetcode 191 - Java | Brian Kernighan's Algorithm'
Code With K5KC 6 mins
Number of 1 Bits - Leetcode 191 - Java | Brian Kernighan's Algorithm
YouTube video 'Daily Leetcode #1338: Nov 29, 2023 - 191. Number of 1 Bits'
Programming Live with Larry 4 mins
Daily Leetcode #1338: Nov 29, 2023 - 191. Number of 1 Bits
YouTube video 'Can You Find the Number of Set Bits? (LeetCode 191: Number of 1 Bits)'
Code With Zi 3 mins
Can You Find the Number of Set Bits? (LeetCode 191: Number of 1 Bits)
YouTube video 'Number of 1 Bits | LeetCode 191 | Coders Camp'
Coders Camp 8 mins
Number of 1 Bits | LeetCode 191 | Coders Camp
YouTube video 'Solving LeetCode 191. Number of 1 Bits | Bit Manipulation | Easy'
Code Harmony 8 mins
Solving LeetCode 191. Number of 1 Bits | Bit Manipulation | Easy
YouTube video 'Number of 1 Bits | LeetCode 191 | O(1) Solution'
The Code Architect 10 mins
Number of 1 Bits | LeetCode 191 | O(1) Solution
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

7 similar problems

Solved On The Same Day

9 easy 2 medium 16 hard
28 solutions   August 9, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality