Number of 1 Bits
Write a function that takes an unsigned integer and returns the number of ‘1’ bits it has (also known as the Hamming weight).
Example 1:
1 | Input: 11 |
Example 2:
1 | Input: 128 |
思路:求二进制表示中1的个数,只要获得二进制表示再统计其中1的个数即可,利用Integer.toBinaryString()的方法可以解决。
代码如下:
1 | public class Solution { |
还有一种按位与的思路也很不错,贴下代码:
1 | public class Solution { |