温馨提示:本站仅提供公开网络链接索引服务,不存储、不篡改任何第三方内容,所有内容版权归原作者所有
AI智能索引来源:http://www.jianshu.com/p/9870edbbfa37
点击访问原文链接

191. Number of 1 Bits 二进制1的个数 - xingzai - 简书

您的运行环境禁止了 JavaScript 的执行,请开启后重新打开该页面! 191. Number of 1 Bits 二进制1的个数 - xingzai - 简书 精彩文章免费看立即下载191. Number of 1 Bits 二进制1的个数xingzai简书作者2019-04-30 18:24IP属地: 北京题目链接
tag:

easy; Bit; question:
  Write a function that takes an unsigned integer and return the number of '1' bits it has (also known as the Hamming weight).

Example 1:

Input: 00000000000000000000000000001011
Output: 3
Explanation: The input binary string **00000000000000000000000000001011** has a total of three '1' bits.

Example 2:

Input: 00000000000000000000000010000000
Output: 1
Explanation: The input binary string 00000000000000000000000010000000 has a total of one '1' bit.

Example 3:

Input: 11111111111111111111111111111101
Output: 31
Explanation: The input binary string 11111111111111111111111111111101 has a total of thirty one '1' bits.

Note:

Note that in some languages such as Java, there is no unsigned integer type. In this case, the input will be given as signed integer type and should not affect your implementation, as the internal binary representation of the integer is the same whether it is signed or unsigned. In Java, the compiler represents the signed integers using 2's complement notation. Therefore, in Example 3 above the input represents the signed integer -3. Follow up:
If this function is called many times, how would you optimize it?

思路:
  把一个整数减去1,然后与原整数做与运算,会把该整数最右边的一个1变成0,要计算1的个数,就循环上述操作,直到这个数为0为止。代码如下:

class Solution { public: int hammingWeight(uint32_t n) { int res = 0; while (n) { n = n & (n - 1); ++res; } return res; } }; © 著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务 举报 上一篇下一篇×下载简书,随时随地看好文友情链接 更多 美国西雅图攻略投资一家宠物酒店需要多少钱?石林峡风景区适合带宠物一起游玩吗?利川腾龙洞风景区带子真的有那么好吃吗?上海生日免费的景点你家宠物能帮忙驱蚊吗?这些驱蚊小技巧让毛孩子变身驱蚊小卫士!哈密旅游景点大全广州去武汉攻略高铁可以托运狗狗吗?狗半岁不吃狗粮怎么办国产狗粮怎么选?豆柴适合你家狗狗吗?如何正确使用宠物体温计为爱宠测量体温?热饮的品种和做法欧洲买表攻略电饭煲做板栗的做法泸州有什么特产狗狗可以每天吃肉吗?宠物饮食的必知小贴士昆明到版纳自驾游狗狗被猫咬了该怎么办?猫咪怀孕周期计算虎皮豆腐做法英伟达市场份额:高端芯片从 95% 到 0%,太惨烈佳木斯风景区适合带宠物一起游玩吗?观山湖公园有什么秘密狗狗总是不吃饭怎么办狗粮中的钙含量充足吗?高百丈风景区好玩吗狗狗的年龄怎么计算才准确?庐山自驾旅游攻略创作你的创作,接受世界的赞赏登录|打开App|热门文章 下载简书,随时随地看好文

智能索引记录