leedcode 191 Hamming Weight

191.

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

Java code

int hammingweight(int n)  //因为是32位,所以n要看做无符号整数

{

  int sum =0;  

  while(n!=0){

    if(n&1==1)

    sum++;

    n>>>1;  //n无符号右移一位,即左边补0;注意与>>的区别,>>是有符号右移,例 1001>>1=1000;而1001>>>1=0000

  }

  return sum;

}

时间: 2024-08-14 00:08:29

leedcode 191 Hamming Weight的相关文章

Hamming Weight的算法分析

看代码时遇到一个求32bit二进制数中1的个数的问题,感觉算法很奇妙,特记录学习心得于此,备忘. 计算一个64bit二进制数中1的个数. 解决这个问题的算法不难,很自然就可以想到,但是要给出问题的最优解,却很有难度. 通常,最容易想到的算法是除余法,继而考虑到除法的代价较高,而且除数是2,会想到使用向右移位来代替除法,并使用&0x1操作来取末位的值,这样提高了算法的效率.然而,这样仍然进行了63次&操作.63次移位操作和63次+操作.若假设字长大小不限,记作N,那么上述算法的时间复杂度都为

[leedcode 191] 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). For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should retu

Hamming Weight的算法分析(转载)

看代码时遇到一个求32bit二进制数中1的个数的问题,感觉算法很奇妙,特记录学习心得于此,备忘. 计算一个64bit二进制数中1的个数. 解决这个问题的算法不难,很自然就可以想到,但是要给出问题的最优解,却很有难度. 通常,最容易想到的算法是除余法,继而考虑到除法的代价较高,而且除数是2,会想到使用向右移位来代替除法,并使用&0x1操作来取末位的值,这样提高了算法的效率.然而,这样仍然进行了63次&操作.63次移位操作和63次+操作.若假设字长大小不限,记作N,那么上述算法的时间复杂度都为

leetcode 191

191. 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). For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so th

338. Counting Bits && 191. Number of 1 Bits

Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1's in their binary representation and return them as an array. Example:For num = 5 you should return [0,1,1,2,1,2]. Follow up: It is very e

191. 求1的位数 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). For example, the 32-bit integer '11' has binary representation 00000000000000000000000000001011, so the function should retu

LeetCode 191:number of one bits

题目就是: 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 shoul

191 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). For example, the 32-bit integer '11' has binary representation 00000000000000000000000000001011, so the function should retu

LeetCode 191. Number of 1 bits (位1的数量)

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 retu