美文网首页
Bit Counting

Bit Counting

作者: Magicach | 来源:发表于2017-12-26 23:19 被阅读0次

Write a function that takes an (unsigned) integer as input, and returns the number of bits that are equal to one in the binary representation of that number.

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

Good Solution1:

public class BitCounting {

  public static int countBits(int n){
    
    return Integer.bitCount(n);
  }
  
}

Good Solution2:

public class BitCounting {

  public static int countBits(int n){
    int ret = n % 2;
    while ((n /= 2) > 0) ret += n % 2;
    return ret;
  }
  
}

Good Solution3:

public class BitCounting {

  public static int countBits(int n){
    return (int) Integer.toBinaryString(n).chars()
              .filter(c -> c == '1')
              .count();
  }
  
}

相关文章

网友评论

      本文标题:Bit Counting

      本文链接:https://www.haomeiwen.com/subject/prcygxtx.html