Advertisement
MiroJoseph

Bit Counting

Apr 4th, 2020
261
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 0.41 KB | None | 0 0
  1. My:
  2. object Kata {
  3.  
  4. def countBits(n: Int): Int = {
  5.   def counting(n: Int, bits: Int=0):Int =
  6.   {
  7.     if(n/2!=0)
  8.       if(n%2==1) counting(n/2, bits+1)
  9.       else counting(n/2, bits)
  10.     else bits+1
  11.   }
  12.   if(n==0) 0
  13.   else
  14.     counting(n)
  15. }
  16. }
  17.  
  18. Other:
  19. object Kata {
  20.   def countBits(n: Int): Int = Integer.bitCount(n)
  21. }
  22.  
  23. object Kata {
  24.   def countBits(n: Int): Int = n.toBinaryString.count(_ == '1')
  25. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement