博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[leetcode-191-Number of 1 Bits]
阅读量:7123 次
发布时间:2019-06-28

本文共 1144 字,大约阅读时间需要 3 分钟。

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

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

 

思路1:向右移位,判断最后一位即可。

思路2:

 n & (n - 1) drops the lowest set bit. It's a neat little bit trick.

Let's use n = 00101100 as an example. This binary representation has three 1s.

If n = 00101100, then n - 1 = 00101011, so n & (n - 1) = 00101100 & 00101011 = 00101000. Count = 1.

If n = 00101000, then n - 1 = 00100111, so n & (n - 1) = 00101000 & 00100111 = 00100000. Count = 2.

If n = 00100000, then n - 1 = 00011111, so n & (n - 1) = 00100000 & 00011111 = 00000000. Count = 3.

n is now zero, so the while loop ends, and the final count (the numbers of set bits) is returned.

int hammingWeight(int n) {  int weight = 0;    while(n != 0)    {       if(n & 1 == 1)weight++;       n>>=1;    }    return weight;         }int hammingWeight(uint32_t n) {    int count = 0;        while (n) {        n &= (n - 1);        count++;    }        return count;}

参考:

 

转载于:https://www.cnblogs.com/hellowooorld/p/6880578.html

你可能感兴趣的文章
git命令行下怎么查看当前分支是基于哪一个分支的,以决定是否可以执行git rebase...
查看>>
wemall 2.0 beta 公测版
查看>>
解决tomcat启动超时
查看>>
程序员必备:项目时间估算技能
查看>>
Shell编程,read的用法
查看>>
gulp koa nodejs 实现的前段工程分离开发
查看>>
MySQL/HandlerSocket和VoltDB:NoSQL的竞争者
查看>>
Inside AbstractQueuedSynchronizer (2)
查看>>
VC组件之间的通信所需的端口
查看>>
POI操作Excel导入导出
查看>>
MFC edit control 用法
查看>>
Server SSL certificate verification failed: certificate issued for a different hostname, issuer is
查看>>
为什么无法从prototype修改constructor 函数
查看>>
音符频率表
查看>>
Android Activity之间数据的传递
查看>>
sql server 调用系统DOS命令
查看>>
在eclipse adt中查看手机中应用的ui布局
查看>>
makefile中的 ifeq ifneq ifdef ifndef条件判断
查看>>
读完这100篇论文 就能成大数据高手
查看>>
Ubuntu单系统(一):苦难深重的校园网
查看>>