当前位置:网站首页>二进制中1的个数
二进制中1的个数
2022-08-02 13:04:00 【龙崎流河】
题目:
编写一个函数,输入是一个无符号整数(以二进制串的形式),返回其二进制表达式中数字位数为 ‘1’ 的个数(也被称为 汉明重量).)。
提示:
请注意,在某些语言(如 Java)中,没有无符号整数类型。在这种情况下,输入和输出都将被指定为有符号整数类型,并且不应影响您的实现,因为无论整数是有符号的还是无符号的,其内部的二进制表示形式都是相同的。
在 Java 中,编译器使用 二进制补码 记法来表示有符号整数。因此,在上面的 示例 3 中,输入表示有符号整数 -3。
示例一:
输入:n = 11 (控制台输入 00000000000000000000000000001011)
输出:3
解释:输入的二进制串 00000000000000000000000000001011 中,共有三位为 ‘1’。
示例二:
输入:n = 128 (控制台输入 00000000000000000000000010000000)
输出:1
解释:输入的二进制串 00000000000000000000000010000000 中,共有一位为 ‘1’。
示例三:
输入:n = 4294967293 (控制台输入 11111111111111111111111111111101,部分语言中 n = -3)
输出:31
解释:输入的二进制串 11111111111111111111111111111101 中,共有 31 位为 ‘1’。
分析:
只需要记住一个公式n = n & (n-1)
可以消除掉二进制数中最右边的1。
代码:
public class HammingWeight {
public int hammingWeight(int n) {
int sum = 0;
while (n != 0) {
n = n & (n-1);
sum++;
}
return sum;
}
}
边栏推荐
- Basic operations of openGauss database (super detailed)
- Wireless vibrating wire acquisition instrument remote modification method
- [b01lers2020]Welcome to Earth-1
- 自媒体创作怎样提高原创度,打造爆款作品?
- Do you know Dijkstra of graph theory?
- Cannot determine loading status from target frame detached when selenium chrome driver is running
- 【C语言】手撕循环结构 ——do...while语句及循环练习题(1)
- Introduction to Graph Neural Networks (GNN) "Recommended Collection"
- The uniapp/applet onload method executes the interpretation every time the page is opened
- 【622. 设计循环队列】
猜你喜欢
随机推荐
你知道图论的Dijkstra吗?
Oracle数据库的闪回技术
Four seasons of trees realized by svg
Seata分布式事务
scrapy框架初识1
工厂方法模式
qt 编译报错 No rule to make target
In-depth analysis and use of Ribbon load balancing
Scala基础语法入门(三)Scala中的各种运算符
LeetCode_139_word split
最小割和对偶图(未完成)
How to use the database like tap water?|Tencent Cloud Database TDSQL-C
国产 GPU 创业潮 喧嚣下的资本游戏
【C语言】夏日一题 —— 如何判断素数?
微信小程序getPhoneNumber接口code=40013
高效代码静态测试工具Klocwork 2022.2——Portal全新升级、支持RLM
自动生成代码器推荐-code-gen
什么是 commonjs2
wx-wow(微信小程序动效库)
80篇国产数据库实操文档汇总(含TiDB、达梦、openGauss等)