Leetcode191. 位1的个数

【简单】力扣算法题解析LeetCode191:位1的个数 本文介绍计算整数二进制中1的个数(汉明重量)的高效解法。核心使用Brian Kernighan算法,通过n= (n - 1)逐次消除最低位1,时间复杂度O(k)(k为1的个数)。对于多次调用场景,提出查表法优化:预计算0-255的汉明重量表,将32位数分为4个8位段查表求和,实现O(1)时间复杂度。代码提供Java实现,并通过示例演示运算过程。进阶方法显著提升重复计算性能,空间仅需256字节。 关键词:汉明重量、位运算、Brian Kernighan算法、查表法、位操作优化 阅读详情

Every day a leetcode

题目来源:191. 位1的个数

解法1:位运算

循环检查给定整数 n 的二进制位的每一位是否为 1。

当检查第 i 位时,我们可以让 n 与 2i 进行与(&)运算,当且仅当 n 的第 i 位为 1 时,运算结果不为 0。

设置一个计数器,遍历一次即可得到位 1 的个数。

注意:1 << i 必须是 uint32_t 的。

代码:

int hammingWeight(uint32_t n) {
    int ans=0;
    for(int i=0;i<32;i++)
    {
        if(n & ((uint32_t)1<<i)) ans++;
    }
    return ans;
}

结果:

在这里插入图片描述

复杂度分析:

时间复杂度:O(k),k=32,是 int 的位数。

空间复杂度:O(1)。

解法2:位运算

我们发现:n & (n-1),它能将 n 的二进制表示的最低位 1 移除。

于是,我们可以一直执行这个操作,直到 n 变成 0,设置一个计数器统计操作次数,即为位 1 的个数。

代码:

int hammingWeight(uint32_t n) {
    int ans=0;
    while(n)
    {
        n=n & (n-1);
        ans++;
    }
    return ans;
}

结果:
在这里插入图片描述

这样做可以节省时间,不需要每一位都判断。

复杂度分析:

时间复杂度:O(log n)。

空间复杂度:O(1)。

三相SVPWM逆变器双闭环PI解耦控制:从dq坐标系到参数整定实战 本文深入解析了三相SVPWM逆变器的双闭环PI解耦控制技术。通过引入dq坐标系,将交流量转换为直流量,并结合前馈补偿实现电流环的解耦控制。文章详细阐述了从数学模型推导、控制器设计到参数整定与SVPWM实现的完整流程,为工程师提供了从理论到实战的系统性指导。 阅读详情

相关推荐

告别调试烦恼:用Lattice Diamond手把手教你JTAG烧录FPGA(附SRAM/Flash模式详解)

本文详细介绍了使用Lattice Diamond软件进行JTAG烧录FPGA的全流程,包括SRAM临时调试和Flash固化的核心区别。从环境准备、硬件连接到文件准备、烧录模式选择,再到典型问题排查和高级技巧,手把手教你快速掌握FPGA烧录技术,提升开发效率。

weixin_42569329的博客 506

LeetCode 191:位1的个数

LeetCode 191:位1的个数题目描述解题思路代码实现总结 题目描述 编写一个函数,输入是一个无符号整数,返回其二进制表达式中数字位数为 ‘1’ 的个数(也被称为汉明重量)。 示例 1: 输入:00000000000000000000000000001011 输出:3 解释:输入的二进制串 00000000000000000000000000001011 中,共有三位为 ‘1’。 示例 2:...

香农三定律的博客 241

《第二十二篇》Cross-Attention:注意力机制详解-代码实现和公式详解《二》

本文详细介绍了Cross-Attention的原理、公式和实现。Cross-Attention用于Transformer解码器和Encoder-Decoder结构,通过查询向量(Q)与键、值向量(K、V)的交互实现序列对齐。核心公式为softmax(QK^T/√d_k)V,其中Q来自Decoder,K、V来自Encoder。文章还给出了多头注意力机制公式和PyTorch实现代码,包括投影计算、注意力分数计算和输出处理。代码示例展示了如何构建一个完整的Cross-Attention模块,并演示了其在解码器查询

guoguozgw的博客 2218

【每日一道LeetCode】——191. 位1的个数

【每日一道LeetCode】——191. 位1的个数

yanxiang3306 2202

Unity 游戏实例开发集合 之 Car Racing 2D (2D赛车) 休闲小游戏快速实现

Unity 游戏实例开发集合 之 Car Racing 2D (2D赛车) 休闲小游戏快速实现 目录 Unity 游戏实例开发集合 之 Car Racing 2D (2D赛车) 休闲小游戏快速实现 一、简单介绍 二、Car Racing 2D (2D赛车) 游戏内容与操作 三、相关说明 四、游戏代码框架 五、知识点 六、游戏效果预览 七、实现步骤 八、工程源码地址 九、延伸扩展 一、简单介绍 Unity 游戏实例开发集合,使用简单易懂的方式,讲解常见游戏的开发实现过程,方便

仙魁XAN 7709

SAR动目标检测三剑客:DPCA/ATI/STAP技术选型指南(含2023最新实验数据对比)

本文深入对比了SAR动目标检测三大主流技术DPCA、ATI与STAP的核心原理与性能差异。基于2023年最新实验数据,分析了它们在最小可检测速度、测速精度、计算复杂度及对通道失配敏感度等方面的优劣,并结合海洋监视与城市交通监控等典型场景,提供了具体的技术选型指南与工程落地考量。

m5n6o7的博客 301

【LeetCode每日一题】——191.位1的个数

编写一个函数,输入是一个无符号整数(以二进制串的形式),返回其二进制表达式中数字位数为 '1' 的个数(也被称为汉明重量)。 提示: 请注意,在某些语言(如 Java)中,没有无符号整数类型。在这种情况下,输入和输出都将被指定为有符号整数类型,并且不应影响您的实现,因为无论整数是有符号的还是无符号的,其内部的二进制表示形式都是相同的。 在 Java 中,编译器使用二进制补码记法来表示有符号整数。因此,在 示例 3 中,输入表示有符号整数 -3。

IronmanJay 676

Win64 驱动内核编程-16.WFP网络监控驱动(防火墙)

WFP驱动监控网络 WFP是微软推出来替代TDIHOOK、NDISHOOK等拦截网络通信的方案,WFP的框架非常庞大,在RING3和RING0各有一套类似的函数,令人兴奋的是,即使在R3使用WFP,也可以做到全局拦截访问网络。由于WFP的范围太广,实在难以一言概括,感...

墨鱼菜鸡 1043

[leetcode] 191. 位1的个数

编写一个函数,输入是一个无符号整数(以二进制串的形式),返回其二进制表达式中设置位的个数(也被称为汉明重量)。

Learning from the mistakes 420

银河麒麟V10安装docker

最近在做的一个信创项目使用的操作系统是银河麒麟高级服务器V10,在安装docker时,会遇到下面的错误。 nothing provides fuse-overlayfs >= 0.7 needed by docker-ce-rootless-extras-20.10.0-3.el7.x86_64 经过分析,以下依赖包是centos系统中的包,所以需要给kylinos创建一个合适的centos源。经过实验,Kylin Linux Advanced Server V1

m0_38004228的博客 4916

基于STM32的太阳能充电宝设计_资料编号31

系统硬件包括主控 STM32F103C8T6、0.96 OLED 显示屏、蜂鸣器、电源自锁开关、温度传感器 DS18B20、继电器、5 V DC 升压模块 、TB4056、18650锂电池、9 V太阳能板、稳压降压 5 V三极管。电源供应:锂电池为系统供电,9 伏太阳能板经 5 伏降压稳压三极管降压为 5 伏后传送到 TP4056,TP4056 为锂电池供电,因锂电池电压 3.7 伏,通过 5 伏 DC 升压模块升压到 5 伏为整个系统提供 5 伏电压。

嵌入式阿齐Archie 1万+

【LeetCode-简单】191. 位1的个数 - 位运算

191. 位1的个数 解法一:循环检查二进制位 直接循环检查给定整数 n 的二进制位的每一位是否为 1。 当检查第 i 位时,让 n 与 1<<i 进行与运算,当且仅当 n 的第 i 位为 1 时,运算结果不为 0。

ASDF的博客 356

《QGIS快速入门与应用基础》161:面要素顶点编辑与形状调整

本文系统讲解了QGIS中面要素顶点编辑与形状调整的核心操作。首先明确了顶点编辑的适用场景与核心概念,强调需满足图层类型、编辑模式、要素选择等六大前提。详细介绍了编辑顶点工具(F2键)的激活路径及配套辅助工具,通过耕地地块修正案例,分步骤演示顶点移动、添加(双击/工具栏)、删除(Delete键)三大基础操作。同时提供捕捉工具开启、画布缩放等实用技巧,帮助用户高效完成面要素的精细化调整,解决实际工作中的形状偏差问题。全文图文结合,步骤清晰,适合GIS新手快速掌握面要素编辑的核心技能。

LuckyHanMo的博客 502

LeetCode191-位1的个数

LeetCode191-位1的个数 题目 编写一个函数,输入是一个无符号整数,返回其二进制表达式中数字位数为 ‘1’ 的个数(也被称为汉明重量)。 输入:00000000000000000000000000001011 输出:3 解释:输入的二进制串 00000000000000000000000000001011 中,共有三位为 ‘1’。 输入:00000000000000000000000010000000 输出:1 解释:输入的二进制串 00000000000000000000000010000

viva_la__vida的博客 198

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

SAP B1中文培訓教材_SDK

公司内部培训资料,对开发工具 ,DIAPI, UIAPI,Add-ON有详细解说

LeetCode第191题_位1的个数

编写一个函数,输入是一个无符号整数(以二进制串的形式),返回其二进制表达式中数字位数为 ‘1’ 的个数(也被称为汉明重量)。

qq_40263592的博客 1194

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

Leetcode 191. 位1的个数 ——题解

Leetcode 191. 位1的个数 ——题解 编写一个函数,输入是一个无符号整数,返回其二进制表达式中数字位数为 ‘1’ 的个数(也被称为汉明重量)。 示例 1: 输入:00000000000000000000000000001011 输出:3 解释:输入的二进制串 00000000000000000000000000001011 中,共有三位为 ‘1’。 示例 2: 输入:0000000...

weixin_43724807的博客 288

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

leetcode 191. 位1的个数

leetcode 191. 位1的个数 题目描述 编写一个函数,输入是一个无符号整数,返回其二进制表达式中数字位数为 ‘1’ 的个数(也被称为汉明重量)。 示例 1: 输入:00000000000000000000000000001011 输出:3 解释:输入的二进制串 00000000000000000000000000001011 中,共有三位为 ‘1’。 示例 2: 输入:000000000...

EngineerHe的博客 512

LeetCode191——位1的个数

我的LeetCode代码仓:https://github.com/617076674/LeetCode 原题链接:https://leetcode-cn.com/problems/number-of-1-bits/description/ 题目描述: 知识点:位运算 思路一:位运算 JAVA代码: public class Solution { public int ha...

清风阁 304

Leetcode191--位1的个数(含多种解法和图解分析)

Leetcode191–位1的个数 编写一个函数,输入是一个无符号整数,返回其二进制表达式中数字位数为 ‘1’ 的个数(也被称为汉明重量)。 作者:黑暗主宰 邮箱:shengzhanhe@gmail.com 文章目录Leetcode191--位1的个数题目描述解题思路 Leetcode191–位1的个数 题目描述 原题链接: ​ https://leetcode-cn.com/problems/...

EngineerHe的博客 727

LeetCode 191. 位1的个数

我的LeetCode:https://leetcode-cn.com/u/ituring/ 我的LeetCode刷题源码[GitHub]:https://github.com/izhoujie/Algorithmcii LeetCode 191. 位1的个数 题目 编写一个函数,输入是一个无符号整数,返回其二进制表达式中数字位数为 ‘1’的个数(也被称为汉明重量)。 示例 1: 输入:0000...

iTuring_Zhou的专栏 53

题解:LeetCode 191.位1的个数

题解:LeetCode 191.位1的个数

SolitudeAlma的博客 181

golang力扣leetcode 191.位1的个数

191.位1的个数191.位1的个数题解代码 191.位1的个数 191.位1的个数 题解 求一个数的二进制中1的个数,每次去除末尾1判断是否等于0即可,大水题 代码 package main func hammingWeight(num uint32) int { cnt := 0 for num != 0 { num = num & (num - 1) cnt++ } return cnt } ...

清风 428

LeetCode刷题-191. 位1的个数

难度:简单⭐️⭐️⭐️。

快乐的小小程序猿 401

LeetCode 图解 | 191.位 1 的个数

点击上方蓝字设为星标下面开始今天的学习~今天分享的题目来源于 LeetCode 上第 191 号问题:位 1 的个数。题目描述编写一个函数,输入是一个无符号整数,返回其二进制表达式中数字...

程序员吴师兄的博客 394

leetcode-191. 位1的个数

leetcode-191. 位1的个数 题目: 代码: #include <iostream> using namespace std; int hammingWeight(uint32_t n){ int count=0; for(int i=0;i<32;i++){ if(n & (1<<i)){ count++; } } return count; } int main(){ int count=0; count = hamming

qq_42250642的博客 447
上一篇: Leetcode231. 2 的幂
下一篇: Leetcode190. 颠倒二进制位
UestcXiye
博客等级 码龄8年 9047粉丝 1306原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

UestcXiye

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址