Skip to content

Latest commit

 

History

History
78 lines (46 loc) · 1.27 KB

File metadata and controls

78 lines (46 loc) · 1.27 KB

LeetCode – 191. Number of 1 Bits

Problem Statement

You are given an integer n, and you must return the number of 1 bits in its binary representation.
This is also known as the Hamming Weight.

Description

  • Convert the number to binary and count all bits that are equal to 1.

  • The input may be large, but bitwise operations make it efficient.

Input

An integer n (32-bit unsigned value).

Output

An integer representing the number of 1 bits in the binary form of n.

Examples

Example 1
Input:
n = 11
Binary: 1011

Output:
3

Explanation:
There are three 1s (1 + 1 + 1).

Example 2
Input:
n = 128
Binary: 10000000

Output:
1

Example 3
Input:
n = 0
Binary: 0

Output:
0

Constraints

  • Input fits in 32-bit unsigned integer.

  • n ≥ 0

Hints

  • Use bitwise AND operation: n & 1 checks the last bit.

  • Right shift n until it becomes 0.

  • Or use the trick: n = n & (n - 1) removes the lowest 1-bit.

Explanation

The simplest approach is to repeatedly check the last bit:

  • Count += n & 1

  • Right shift n (n = n >> 1)

Or use the optimized approach:

  • Every time you do n = n & (n - 1), you remove one 1-bit.

  • Count how many times this operation runs.