Number of 1 Bits
来源:互联网 发布:aerial mac 编辑:程序博客网 时间:2024/06/11 08:27
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。比较容易想到的是用循环,利用n>>2,每次与1相与,来解决问题。还有一个比较好的思路:类似于剑指offer中提到的,利用n = n & (n-1),这样n中有几个1,就循环几次,省时间。
c++版如下:
class Solution {public: int hammingWeight(uint32_t n) { int count = 0; while (n) { ++ count; n = (n - 1) & n; } return count; }};
Java版
public class Solution { // you need to treat n as an unsigned value public int hammingWeight(int n) { int count = 0; while(n!=0) { count++; n = n & (n-1); } return count; }}或者
public class Solution { // you need to treat n as an unsigned value public int hammingWeight(int n) { String s = Integer.toBinaryString(n); int count = 0; char[] cset = s.toCharArray(); for(char c:cset) { if(c-'1'==0) { count++; } } return count; }}不过Java确实比c++慢很多。。。。
0 0
- Number of 1 Bits
- Number of 1 Bits
- Number of 1 Bits
- Number of 1 Bits
- Number of 1Bits
- Number of 1 Bits
- Number of 1 Bits
- Number of 1 Bits
- Number of 1 Bits
- Number of 1 Bits
- Number of 1 Bits
- Number of 1 Bits
- Number of 1 Bits
- Number of 1 Bits
- Number of 1 Bits
- Number of 1 Bits
- Number of 1 Bits
- Number of 1 Bits
- Android-Volley网络请求流程图
- 日经社説 20150521 好循環促し中長期の成長基盤を固めたい
- 记一次内存优化的分享
- react 事件系统
- iOS 值得关注的开源项目
- Number of 1 Bits
- java 发送http请求
- 程序代码在运行前与运行时的内存分布情况
- camera摄像原理之四:曝光和GAMMA
- P2P协议概述
- 自定义圆角矩形、圆形
- java获取 cup信息
- 无密钥登录的自动脚本实现(ssh-copy-id、expect免交互输入脚本)
- linux系统中如何进入退出vim编辑器,方法及区别