LeetCode 191. Number of 1 Bits
来源:互联网 发布:找网络推手联系方式 编辑:程序博客网 时间:2024/04/27 23:36
Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as theHamming weight).
For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011
, so the function should return 3.
// Need to pay attention to operators precedence and associativity, + and & are left to right associative. + precedence is higher than &. It is always good to add parenthesis if can't name the precedence and associativity.
int hammingWeight(uint32_t x) { x = ((x & 0x55555555) + ((x >> 1) & 0x55555555)); x = ((x & 0x33333333) + ((x >> 2) & 0x33333333)); x = ((x & 0x0f0f0f0f) + ((x >> 4) & 0x0f0f0f0f)); x = ((x & 0x00ff00ff) + ((x >> 8) & 0x00ff00ff)); x = ((x & 0x0000ffff) + ((x >> 16) & 0x0000ffff)); return x; }// Another version.// it takes advantage of n & (n-1) which flips the right most '1' into '0'int countOneBits(int n) { int count = 0; while(n) { count++; n = n & (n-1); } return count;}
0 0
- 191. Number of 1 Bits Leetcode Python
- 【LeetCode】191.Number of 1 Bits
- [LeetCode]191.Number of 1 Bits
- LeetCode 191. Number of 1 Bits
- LeetCode 191. Number of 1 Bits
- [leetcode] 191. Number of 1 Bits
- <LeetCode OJ> 191. Number of 1 Bits
- Leetcode 191. Number of 1 Bits
- leetCode 191. Number of 1 Bits
- 191. Number of 1 Bits LeetCode
- Leetcode: 191. Number of 1 Bits(JAVA)
- LeetCode 191. Number of 1 Bits
- [LeetCode]191. Number of 1 Bits
- leetcode 191. Number of 1 Bits
- LeetCode *** 191. Number of 1 Bits
- [LeetCode]191. Number of 1 Bits
- LeetCode 191. Number of 1 Bits
- leetcode-191. Number of 1 Bits
- Redis数据淘汰策略
- supervisor 笔记
- javascript杂谈 半整合半原创篇
- codeforce 602C The Two Routes
- Spring中ApplicationContext加载机制和配置初始化
- LeetCode 191. Number of 1 Bits
- C#线程本地存储:LocalDataStoreSlot和ThreadLocal<T>
- 关于Android中Activity之间socket传递的问题
- c++作业3
- Hibernate多对一的双向关联xml配置
- Ubuntu环境下配置ElasticSearch
- NodeJs安装package.json中依赖包失败
- 奋斗_01
- ViewPager(二)——滑动监听器OnPageChangeListener