LeetCode191 Number of 1 Bits
来源:互联网 发布:剑雨江湖进阶数据仙羽 编辑:程序博客网 时间:2024/06/02 05:04
LeetCode191 Number of 1 Bits
问题来源LeetCode191
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.
这道题是计算32bit的int数二进制格式中的1的个数。这个个数又被称为Hamming Weight
Wiki
The Hamming weight of a string is the number of symbols that are different from the zero-symbol of the alphabet used.Hamming Weight是字符串与所使用的字母的零符号不同的符号的数目。
问题分析
这道题很容易就能想到既然是求32bit中二进制的个数,那么也就是位运算。但是题目中给出 // you need to treat n as an unsigned value 也就是无符号的整型。对于Java程序来说,没有无符号整型的概念,那么应该怎么解决呢。大家可以看另外一篇文章[]
这里就是先将int转化为long,然后通过n&0x0FFFFFFFFl运算,保存无符号的整型。然后通过不断的将数进行右移操作,统计非0的个数。
代码如下
// you need to treat n as an unsigned valuepublic int hammingWeight(int n) { long unsignedN = n&0x0FFFFFFFFl; short res = 0; while (unsignedN>0){ if((unsignedN&1)==1) res++; unsignedN>>=1; } return res;}
- LeetCode191 Number of 1 Bits
- LeetCode191:Number of 1 Bits
- LeetCode191 Number of 1 Bits
- LeetCode191——Number of 1 Bits
- LeetCode191:Number of 1 Bits【Java】
- LeetCode191—Number of 1 Bits
- leetcode191[easy]---Number of 1 Bits
- LeetCode191--Bit Manipulation-- Number of 1 Bits(转换为二进制有几个1)
- leetCode191/201/202/136 -Number of 1 Bits/Bitwise AND of Numbers Range/Happy Number/Single Number
- 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
- Single Number III
- 引入Fresco 网络加载图片的学习
- 【Scikit-Learn 中文文档】模型评估: 量化预测的质量
- 如何快速且准确地运用搜索引擎查找资料
- http请求头详解
- LeetCode191 Number of 1 Bits
- Win10 Tensorflow(gpu) 安装详解
- 全球100款大数据工具汇总,入行必备
- Hadoop HDFS的运行原理
- 在实践中深入理解VMware虚拟机的上网模式:桥接模式
- 高可用性hadoop集群的搭建
- 归并排序
- 杭电1228 之 A + B
- BZOJ1034 [ZJOI2008]泡泡堂BNB 【贪心】