LeetCode Number of 1 Bits JAVA

来源:互联网 发布:童装淘宝店名大全 编辑:程序博客网 时间:2024/06/14 18:30

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.

先是考虑之前学到的汉明码,写了下面这个算法:

public class Solution {    // you need to treat n as an unsigned value    public int hammingWeight(int n) {        int num = 0;        if(n==0){            return 0;        }        while(n/2 != 0){            num = num + n%2;            n = n/2;        }        return num+1;    }}
自己调试了一下,好像也没什么问题。提交代码答案的时候,发现出错了。搞半天是题目说的意思是用unsigned int类型。这样,当输入的范围超过int最大值2的32次方以后,就会出现问题了。

后来考虑了一下,这题目比较简单的方法还是使用位运算符比较容易实现。

public class Solution {      // you need to treat n as an unsigned value      public int hammingWeight(int n) {          int count = 0;          for (int i=0; i<32; i++) {              if ((n>>>i & 1) == 1) 
<span style="white-space:pre"></span>count++;          }          return count;      } }


0 0