LeetCode 191 Number of 1 Bits
来源:互联网 发布:mac截图后文件在哪里 编辑:程序博客网 时间:2024/06/06 04:59
题目描述
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.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
分析
1. JDK:int bitCount(int i)
效率肯定高,JDK源码+_+
/** * Returns the number of one-bits in the two's complement binary * representation of the specified {@code int} value. This function is * sometimes referred to as the <i>population count</i>. * * @param i the value whose bits are to be counted * @return the number of one-bits in the two's complement binary * representation of the specified {@code int} value. * @since 1.5 */ public static int bitCount(int i) { // HD, Figure 5-2 i = i - ((i >>> 1) & 0x55555555); i = (i & 0x33333333) + ((i >>> 2) & 0x33333333); i = (i + (i >>> 4)) & 0x0f0f0f0f; i = i + (i >>> 8); i = i + (i >>> 16); return i & 0x3f; }
2. 思路
思路一☹:分别判断每一位,有n位就要判断n次。
思路二☺:有几个1就判断几次。参考如何判断一个数是2的n次方?判断i&(i-1)是不是0即可~
代码
public static int hammingWeight(int n) { int rt = 0; while (n != 0) { n = n & (n - 1); rt++; } return rt; }
1 0
- leetcode:bits:Number of 1 Bits(191)
- [Leetcode 191, Easy] Number of 1 Bits
- leetCode #191 number of 1 bits
- LeetCode 191 Number of 1 Bits
- Leetcode NO.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
- 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
- 【以太网数据结构】UDP协议
- project euler 7
- 忽悠的生态
- project euler 8
- 关于socket阻塞与非阻塞情况下的recv、send、read、write返回值
- LeetCode 191 Number of 1 Bits
- .bash_profile和.bashrc的区别(如何设置生效)
- APUE学习之----socket编程实现简单的C/S
- E-斐波那契数
- 文本分类(二):scrapy爬取网易新闻
- Python中的os模块
- 树莓派(Raspberry pi)下安装七牛云c/c++ SDK时遇到的问题及解决方案
- project euler 9
- 带你走进AJAX(1)