[LeetCode] 191. Number of 1 Bits

标签: leetcode lintcode 面试 bit 九章
208人阅读 评论(0) 收藏 举报
分类:

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.

思路:n和(n-1)按位与可以去掉二进制相对最右边一位1

          经过count次n&(n-1)直到n变为0,count就是n的二进制中表示1的个数

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


查看评论

191. Number of 1 Bits [easy] (Python)

题目链接https://leetcode.com/problems/number-of-1-bits/题目原文 Write a function that takes an unsigned in...
  • coder_orz
  • coder_orz
  • 2016-05-05 15:13:57
  • 1712

[LeetCode-191] Number of 1 Bits(判断一个整数中有多少个1)

方法一:【分析】判断一个整数最右边是不是1,我们可以把输入的整数和1相&,判断相&之后的结果,判断是不是为1,然后继续移位判断其它位 方法二:【分析】上述的方法只适用于正数,当输入的数为一个负数的时候...
  • xy010902100449
  • xy010902100449
  • 2015-09-14 20:42:43
  • 1157

leetcode-191 Number of 1 Bits 二进制数字中1的个数

问题描述: Write a function that takes an unsigned integer and returns the number of ’1' bits it has (als...
  • woliuyunyicai
  • woliuyunyicai
  • 2015-03-10 19:42:25
  • 2944

LeetCode 191 -Number of 1 Bits ( JAVA )

Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also know...
  • UckyK
  • UckyK
  • 2016-04-11 12:50:50
  • 915

Leetcode_191_Number of 1 Bits

本文是在学习中的总结,欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/44486547 Write a function th...
  • pistolove
  • pistolove
  • 2015-03-20 08:11:25
  • 1351

【LeetCode-191】 Number of 1 Bits(C++)

题目要求:求一个数n对应的二进制数中1的位数。 解题思路:我的思路是将n转化为二进制数,在转换的过程中判断当前位是不是1,变转换变计算(1)。在网上搜了一下,发现了另外一种解法,用与操作和右移操作(2...
  • liujiayu1015
  • liujiayu1015
  • 2016-05-20 21:04:27
  • 179

LeetCode191——Number of 1 Bits

Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also know...
  • booirror
  • booirror
  • 2015-03-12 10:53:59
  • 2233

leetcode 191 Number of 1 Bits C++

这个一分钟搞定。 就是要对位运算有一定的了解 乘2相当于整体二进制位左移一位,而且这种运算方式比直接乘要快。 因此只要判断是奇数就加一,然后整体右移一位。 class Solution { pub...
  • a2331046
  • a2331046
  • 2016-05-15 21:11:51
  • 163

Leetcode#191. Number of 1 Bits(位运算)

题目Write a function that takes an unsigned integer and returns the number of ’1’ bits it has (also kn...
  • xunalove
  • xunalove
  • 2017-08-25 15:16:59
  • 218

LeetCode-Number of 1 Bits

问题描述Write a function that takes an unsigned integer and returns the number of ’1’ bits it has (also ...
  • canglingye
  • canglingye
  • 2015-03-10 16:49:19
  • 6373
    个人资料
    持之以恒
    等级:
    访问量: 2万+
    积分: 1150
    排名: 4万+