LearnFree QA courses with practical knowledge checks
All questions

Intermediate · Java · Bit manipulation

Java: count set bits

Java coding interview preparation for QA and SDET roles · ~12 min

This is a Pro program. Practice and solutions require ₹99/month. New coding programs are added every month. Basic programs remain free.

Problem statement

Implement static int setBits(int n).

Count ones in the 32-bit two’s-complement representation, including negative integers.

Input & output

setBits(13) → 3

Interview discussion

  • Explain the time and auxiliary-space complexity of your approach.
  • Which boundary cases matter when testing count set bits?

Java 8 · Bit manipulation. Implement the required static method in class Solution. The test runner checks returned values, including boundary cases; printing a sample alone does not solve the exercise.