DEV Community

Shashi Vardhan
Shashi Vardhan

Posted on

2 2

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

Code(Java)

public static int countBits(int n)

     {

         int count=0;

         String BinaryValues=Integer.toBinaryString(n);

         //System.out.println(BinaryValues);

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

         {

              if(BinaryValues.charAt(i)=='1')

              {

                  count++;

              }

         }

         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 : https://onlylang.blogspot.com/

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay