当前位置:网站首页>剑指 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;
}
};
边栏推荐
- Everything comes to him who waits
- Method overloading and rewriting
- Swift return type is a function of function
- 【Colab】【使用外部数据的7种方法】
- Node. Js: use of express + MySQL
- The solution to change the USB flash disk into a space of only 2m
- [exercise 7] [Database Principle]
- Application of ncnn Neural Network Computing Framework in Orange Pi 3 Lts Development Board
- C graphical tutorial (Fourth Edition)_ Chapter 17 generic: genericsamplep315
- Xctf mobile--app3 problem solving
猜你喜欢
The upward and downward transformation of polymorphism
Leetcode234 palindrome linked list
[problem exploration and solution of one or more filters or listeners failing to start]
Day 1 of kotlin learning: simple built-in types of kotlin
The latest version of blind box mall thinkphp+uniapp
Swift bit operation exercise
社交社区论坛APP超高颜值UI界面
With pictures and texts, summarize the basic review of C language in detail, so that all kinds of knowledge points are clear at a glance?
Analysis of the influence of voltage loop on PFC system performance
Summary of error prone knowledge points: Calculation of define s (x) 3*x*x+1.
随机推荐
RedHat5 安装Socket5代理服务器
C graphical tutorial (Fourth Edition)_ Chapter 17 generic: genericsamplep315
电压环对 PFC 系统性能影响分析
[problem exploration and solution of one or more filters or listeners failing to start]
OpenStack节点地址改变
Gan totem column bridgeless boost PFC (single phase) seven PFC duty cycle feedforward
[judgment question] [short answer question] [Database Principle]
Togaf certification self-study classic v2.0
4. Wireless in vivo nano network: electromagnetic propagation model and key points of sensor deployment
十條職場規則
Idea packages the web project into a war package and deploys it to the server to run
Using swift language features, write a pseudo-random number generator casually
Enable SASL authentication for memcached
【习题五】【数据库原理】
【计网】第三章 数据链路层(2)流量控制与可靠传输、停止等待协议、后退N帧协议(GBN)、选择重传协议(SR)
社交社区论坛APP超高颜值UI界面
[exercise 5] [Database Principle]
Loan calculator my pressure is high
How to convert a decimal number to binary in swift
【数据库原理复习题】