Count Set Bits in a Positive Signed Integer

Quick Overview

Count set bits of the source’s positive signed integer by lowest-bit removal and byte-table reuse for repeated calls.

Count Set Bits in a Positive Signed Integer

Company: Google

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: easy

Interview Round: Other

### Problem Return the number of set bits in the binary representation of a positive integer n, also called its Hamming weight. ```cpp int hammingWeight(int n); ``` ### Examples ```text Input: n = 42 Output: 3 ``` Its binary spelling is 101010. ```text Input: n = 1024 Output: 1 ``` ### Constraints - `1 <= n <= 2147483647`. ### Optional follow-up How would you optimize a large number of calls?

Overview: Count set bits of the source’s positive signed integer by lowest-bit removal and byte-table reuse for repeated calls.

Google logo
Google
Date not reported
easySoftware EngineerOtherCoding & Algorithms
0
0

Problem

Return the number of set bits in the binary representation of a positive integer n, also called its Hamming weight.

int hammingWeight(int n);

Examples

Input: n = 42
Output: 3

Its binary spelling is 101010.

Input: n = 1024
Output: 1

Constraints

  • 1 <= n <= 2147483647 .

Optional follow-up

How would you optimize a large number of calls?