Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Count Set Bits in Integer

EasyPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Count Set Bits in Integer. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

A low-level Qualcomm Snapdragon or Hexagon DSP routine may need to count enabled feature flags in a packed 32-bit word. Given a nonnegative 32-bit integer n, return the number of bits equal to 1 in its binary representation.

Use an algorithm that processes only the set bits rather than always examining all 32 positions.

Formal Specification

Implement count_set_bits(n).

  • Input: n, an integer satisfying 0 <= n <= 2^32 - 1.
  • Output: An integer representing the number of set bits in n.
  • The input is treated as an unsigned 32-bit value.
  • Do not convert the integer to a string or use a built-in population-count function.

Constraints

  • 0 <= n <= 4,294,967,295
  • The input represents an unsigned 32-bit integer
  • The result is between 0 and 32 inclusive
  • Do not use string conversion or a built-in population-count function

Function Signature

def count_set_bits(n):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output