Loading

LeetCode problem#191

Number of 1 Bits

Solved in 1 languageJava

Solve it on LeetCode(opens in a new tab)

Solution

13 lines
1class Solution {
2    public int hammingWeight(int n) {
3        int count = 0;
4        while (n != 0) {
5            int digit = n & 1;
6            if (digit == 1) {
7                count++;
8            }
9            n = n >> 1;
10        }
11        return count;
12    }
13}

Want a walkthrough of this Java solution?

Get a step-by-step explanation of the idea behind the code.

All problems

Problem statements belong to LeetCode and are on leetcode.com. We're not affiliated with LeetCode.