Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Count Ones in an Integer

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

Your question is Count Ones in an 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

Broadcom software such as VMware vSphere may inspect integer bitmasks to determine which feature flags are enabled. Given a non-negative integer n, return the number of 1 bits in its binary representation.

Use bitwise operations rather than converting the integer to a binary string. The binary representation should not include leading zeroes.

Formal Specification

Implement count_set_bits(n):

  • Input: n, a non-negative integer.
  • Output: An integer equal to the number of set bits, or 1 bits, in n.

Constraints

  • 0 <= n <= 2^31 - 1
  • The input is an integer
  • Use bitwise operations instead of string conversion
  • Use O(1) auxiliary space

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