设为首页 加入收藏

TOP

[LeetCode]191.Number of 1 Bits
2015-11-21 01:04:55 来源: 作者: 【 】 浏览:2
Tags:LeetCode 191.Number 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 return 3.

思路

每次左移一位,进行&运算。

代码

/*------------------------------------------------------
*   日期:2014-04-12
*   作者:SJF0115
*   题目: 191.Number of 1 Bits
*   网址:https://leetcode.com/problems/number-of-1-bits/
*   结果:AC
*   来源:LeetCode
*   博客:
--------------------------------------------------------*/
#include 
   
     #include 
    
      using namespace std; class Solution { public: int hammingWeight(uint32_t n) { if(n == 0){ return 0; }//if if(n == 1){ return 1; }//if int count = 0; for(int i = 0;i < 32;++i){ if((n&(1<
     
       0){ ++count; }//if }//for return count; } }; int main(){ Solution solution; uint32_t num = 1; cout<<""<
      
     
    
   

思路二

每执行一次x = x&(x-1),会将x用二进制表示时最右边的一个1变为0,因为x-1将会将该位(x用二进制表示时最右边的一个1)变为0。

代码二

/*------------------------------------------------------ * 日期:2014-04-12 * 作者:SJF0115 * 题目: 191.Number of 1 Bits * 网址:https://leetcode.com/problems/number-of-1-bits/ * 结果:AC * 来源:LeetCode * 博客: --------------------------------------------------------*/ #include 
    
      #include 
     
       using namespace std; class Solution { public: int hammingWeight(int n) { int count = 0; while(n != 0){ n = n & (n-1); count++; }//while return count; } }; int main(){ Solution solution; uint32_t num = 11; cout<<""<
      
     
    
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇[LeetCode] Find Peak Element 下一篇ZOJ 3865 Superbot BFS

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: