DEV Community

Shashi Vardhan
Shashi Vardhan

Posted on


Bit Counting Codewars

Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number. You can guarantee that input is non-negative.

Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case


public static int countBits(int n)


         int count=0;

         String BinaryValues=Integer.toBinaryString(n);


         for(int i=0;i<BinaryValues.length();i++)







         return count;


Enter fullscreen mode Exit fullscreen mode

Solution 2:

public static int countBits(int n){

    return Integer.bitCount(n);

Enter fullscreen mode Exit fullscreen mode

More at :

Top comments (0)

Timeless DEV post...

Git Concepts I Wish I Knew Years Ago

The most used technology by developers is not Javascript.

It's not Python or HTML.

It hardly even gets mentioned in interviews or listed as a pre-requisite for jobs.

I'm talking about Git and version control of course.

One does not simply learn git