Bit Counting

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();
  }
  
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 你说他要走了。 你不舍。 我也不舍。 我想要这世间皆圆满, 莫别离。 我想要这生活多温柔, 莫烦忧。 我想要你那里...
    晴朗的小白阅读 238评论 1 3
  • 晚上儿子指着平板说要看超级飞侠,我告诉他平板开不了机,坏了。然后问他,谁弄坏的?他回答说,豆豆弄坏的。 有时喝水时...
    山河万朵阅读 569评论 0 4
  • 我于广西柳州通过部分视频资料学习王坤老师主讲的“有效演讲艺术”课程,从2017年5月23日开始第二阶段演...
    韦俐莎阅读 191评论 3 1