Number of 1 Bits

来源:互联网 发布:aerial mac 编辑:程序博客网 时间:2024/06/11 08:27

Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).

For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3.

Credits:

Special thanks to @ts for adding this problem and creating all test cases.

主要思路就是:输入一个(正)数,求这个正数的二进制表示中有多少个1。比较容易想到的是用循环,利用n>>2,每次与1相与,来解决问题。还有一个比较好的思路:类似于剑指offer中提到的,利用n = n & (n-1),这样n中有几个1,就循环几次,省时间。

c++版如下:

class Solution {public:  int hammingWeight(uint32_t n) {    int count = 0;  while (n)  {    ++ count;    n = (n - 1) & n;  }  return count;  }};

Java版

public class Solution {    // you need to treat n as an unsigned value    public int hammingWeight(int n) {        int count = 0;        while(n!=0) {            count++;            n = n & (n-1);        }                return count;    }}
或者

public class Solution {    // you need to treat n as an unsigned value    public int hammingWeight(int n) {            String s = Integer.toBinaryString(n);        int count = 0;        char[] cset = s.toCharArray();        for(char c:cset) {            if(c-'1'==0) {                count++;            }        }        return count;            }}
不过Java确实比c++慢很多。。。。


0 0