当前位置:网站首页>剑指 Offer 15. 二进制中1的个数
剑指 Offer 15. 二进制中1的个数
2022-07-03 12:10:00 【嗝~~~~】
剑指 Offer 15. 二进制中1的个数
难度简单251
编写一个函数,输入是一个无符号整数(以二进制串的形式),返回其二进制表达式中数字位数为 ‘1’ 的个数(也被称为 汉明重量).)。
提示:
- 请注意,在某些语言(如 Java)中,没有无符号整数类型。在这种情况下,输入和输出都将被指定为有符号整数类型,并且不应影响您的实现,因为无论整数是有符号的还是无符号的,其内部的二进制表示形式都是相同的。
- 在 Java 中,编译器使用 二进制补码 记法来表示有符号整数。因此,在上面的 示例 3 中,输入表示有符号整数 -3。
示例 1:
输入:n = 11 (控制台输入 00000000000000000000000000001011)输出:3解释:输入的二进制串
00000000000000000000000000001011 中,共有三位为 '1'。
示例 2:
输入:n = 128 (控制台输入 00000000000000000000000010000000)输出:1解释:输入的二进制串 00000000000000000000000010000000 中,共有一位为 '1'。
示例 3:
输入:n = 4294967293 (控制台输入 11111111111111111111111111111101,部分语言中 n = -3)输出:31解释:输入的二进制串 11111111111111111111111111111101 中,共有 31 位为 '1'。
提示:
- 输入必须是长度为 32 的 二进制串 。
代码
class Solution {
public:
int hammingWeight(uint32_t n) {
int flag=0;
while(n){
if(n&1==1)
flag++;
n=n>>1;
}
return flag;
}
};
边栏推荐
- Dix règles de travail
- Idea packages the web project into a war package and deploys it to the server to run
- Method overloading and rewriting
- Analysis of the influence of voltage loop on PFC system performance
- idea将web项目打包成war包并部署到服务器上运行
- Ali & ant self developed IDE
- The foreground uses RSA asymmetric security to encrypt user information
- C graphical tutorial (Fourth Edition)_ Chapter 20 asynchronous programming: examples - cases without asynchronous
- context. Getexternalfilesdir() is compared with the returned path
- 【数据库原理及应用教程(第4版|微课版)陈志泊】【第六章习题】
猜你喜欢

电压环对 PFC 系统性能影响分析

The latest version of blind box mall thinkphp+uniapp

自抗扰控制器七-二阶 LADRC-PLL 结构设计

Four problems and isolation level of MySQL concurrency

Social community forum app ultra-high appearance UI interface

如何在微信小程序中获取用户位置?

Summary of error prone knowledge points: Calculation of define s (x) 3*x*x+1.

【综合题】【数据库原理】

强大的头像制作神器微信小程序

【数据库原理及应用教程(第4版|微课版)陈志泊】【SQLServer2012综合练习】
随机推荐
【计网】第三章 数据链路层(2)流量控制与可靠传输、停止等待协议、后退N帧协议(GBN)、选择重传协议(SR)
Flinksql can directly create tables and read MySQL or Kafka data on the client side, but how can it automatically flow and calculate?
【习题六】【数据库原理】
Quickly learn member inner classes and local inner classes
Exploration of sqoop1.4.4 native incremental import feature
Integer case study of packaging
How to get user location in wechat applet?
alright alright alright
Solve the problem of VI opening files with ^m at the end
Export the entire Oracle Database
[problem exploration and solution of one or more filters or listeners failing to start]
The solution to change the USB flash disk into a space of only 2m
A large select drop-down box, village in Chaoyang District
有限状态机FSM
[exercise 7] [Database Principle]
Enable SASL authentication for memcached
Application of ncnn Neural Network Computing Framework in Orange Pi 3 Lts Development Board
【ArcGIS自定义脚本工具】矢量文件生成扩大矩形面要素
【Colab】【使用外部数据的7种方法】
Drop down refresh conflicts with recyclerview sliding (swiperefreshlayout conflicts with recyclerview sliding)