338. Counting Bits【M】【leetcode题解】

信息学奥赛刷题必备:OpenJudge NOI 4.6 1455题‘An Easy Problem’保姆级解法(附C++代码) 本文深入解析信息学奥赛经典题目OpenJudge NOI 4.6 1455题'An Easy Problem',提供两种高效解法:暴力枚举法和位运算规律法,并附详细C++代码实现。通过数制转换和枚举技巧,帮助参赛者掌握二进制数位操作的核心算法,提升竞赛解题能力。 阅读详情

Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1's in their binary representation and return them as an array.

Example:
For num = 5 you should return [0,1,1,2,1,2].

Follow up:

  • It is very easy to come up with a solution with run time O(n*sizeof(integer)). But can you do it in linear time O(n) /possibly in a single pass?
  • Space complexity should be O(n).
  • Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language.

Show Hint 

  1. Credits:
    Special thanks to @ syedee for adding this problem and creating all test cases.


    Subscribe to see which companies asked this question

    它是有规律地重复的




    class Solution(object):
        def countBits(self, num):
            if num == 0:
                return [0]
            res = [0]
            bit = 0
            temp = num
            while temp > 0:
                temp /= 2
                bit += 1
            #print bit
            for i in xrange(bit-1):
                t_res = []
                for j in res:
                    t_res.append(j+1)
                res = res + t_res
                #print res
            for i in res[:(num - pow(2,bit-1))+1]:
                res.append(i+1)
    
            return res


NetApp 7-mode初始化详解(原AGGR重建)及注意事项 没想到有生之年还能再写个7-mode的文章,上次接触可能已将近十年,本次恰巧碰到这个机会,边学习边整理,整整一天时间,碰到了不少坑,作为记录。 阅读详情

相关推荐

Matlab图像处理频域滤波实现——高斯低通、高通、带通带阻滤波器

如果你想要进一步了解更多的相关知识,

小嘤熊的博客 1万+

LeetCode:338. Counting Bits

LeetCode:338. Counting Bits Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1's in their binary representation and return them as an array...

Wisimer 207

comfyui从入门到精通二:提示词规则详解

《AI绘画提示词使用全指南》摘要: 本文系统解析AI绘画提示词的核心规则与实用技巧。关键点包括:1) 空格与下划线的本质差异,webui会自动转换但comfyui保留原格式;2) 数字与单词表达(如1girl/one girl)会导致风格变化;3) 三种权重控制方式(数值标注、括号嵌套、位置效应),其中数值标注最直观有效;4) 位置衰减公式揭示提示词排序对效果的影响权重。同时指出当前AI绘画仍存在角色一致性等更复杂的技术瓶颈。全文通过多组对比实验,为创作者提供从基础语法到高阶控制的完整解决方案。

ScottePerk的博客 1934

LeetCode 338.Counting Bits 解题报告

LeetCode 338.Counting Bits 解题报告

骆小坑的填坑之旅 579

OpenCL编译环境配置

在 Linux 系统上配置 OpenCL 开发环境需要安装适当的驱动、运行时和开发工具。

深之JohnChen的专栏 2003

物理信息神经网络(PINNs)在交通运输领域的应用

物理信息神经网络(PINNs)在交通运输领域的应用研究结合了数据驱动与物理模型约束,通过嵌入交通流守恒定律等物理信息,显著提升了交通状态估计与预测的精度。该技术仅需少量观测数据(流量、速度、密度等),即可实现高精度建模,尤其适用于数据稀疏场景。研究重点包括:交通状态估计与预测、参数辨识、交通控制优化等领域,同时面临计算成本高、物理模型依赖性等挑战。未来需解决大规模异构数据处理问题,以进一步推动智能交通系统发展。

qq_49609070的博客 944

LeetCode oj 338. Counting Bits(DP)

338. Counting Bits QuestionEditorial Solution My Submissions Total Accepted: 46702 Total Submissions: 79672 Difficulty: Medium Given a non negative integer number num. For every numbers i in the r

Tristeza的博客 460

从零开始:PLUMED与GROMACS整合安装全攻略

本文详细介绍了如何从零开始整合安装PLUMED与GROMACS,包括系统环境检查、MPI配置、PLUMED编译安装、GROMACS补丁应用及常见问题解决方案。通过本教程,研究人员可以快速完成分子动力学模拟工具的整合安装,实现增强采样和自由能计算功能。

weixin_42520796的博客 292

(DP 线性DP) leetcode 338. Counting Bits

Given a non negative integer numbernum. For every numbersiin the range0 ≤ i ≤ numcalculate the number of 1's in their binary representation and return them as an array. Example 1: Input: 2...

123

伪距单点定位推导+DOP值分析(附matlab仿真代码)

伪距单点定位公式推导、DOP值分析与matlab仿真分析

shannanshouyin的博客 2513

《UDS协议从入门到精通》系列——图解0x14:清除诊断信息

图解0x14:清除诊断信息,简洁易懂,迅速上手!

车载系统攻城狮 4825

leetcode338:Counting Bits(medium)

经过一年的雁栖学习,终于回到了实验室,开始了研二的科研生活,是时候把我这一年的所学所想所思记录下来,以后我会慢慢更博,争取把以前和以后的学习生活记录下来! 昨天正式”刷”了第一道leetcode,以前总是断断续续地随意翻着做。 题意:Given a non negative integer number num. For every numbers i in the range 0 ≤

梓jie的博客 508

《QGIS快速入门与应用基础》079:KML/KMZ格式:Google Earth兼容

KML/KMZ是专为地理可视化设计的空间数据格式,原生兼容Google Earth,支持点线面要素标注与多媒体集成。KML为XML文本格式,KMZ是其压缩版本。该格式优势在于可视化表现力强、跨平台共享便捷,适合地理标注、路线分享等场景,但存在属性支持弱、大数据量处理效率低等局限。QGIS中可便捷加载和导出KML/KMZ数据,需注意编码设为UTF-8、勾选"导出样式"以保留可视化效果。建议中小规模标注数据使用KMZ格式,确保关联资源完整,提升共享效率。

LuckyHanMo的博客 769

338. Counting Bits

  从今天开始,每天刷一道leetcode。   今天的题目很简单:Given a non negative integer numbernum. For every numbersiin the range0 ≤ i ≤ numcalculate the number of 1's in their binary representation and return them...

aiqingl97670的博客 117

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

深度学习工具包 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】338. Counting Bits

Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1's in their binary representation and return them as an array. Example: For num = 5

Juxin_Lin的博客 531

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

leetcode 338. Counting Bits

分析打算用动态规划,所以先找x和x-1的规律: 0 1 10 11 100 101 110 111 1000 1001 1010 1010010100101 1010010100110 111 1000f(x) 表示x二进制表示中1的个数, m表示从右往左第一个0的位置(从0开始计数)。找数字x-1 从右往左第一个0的位置m;f(x) = f(x-1) - m + 1

不积跬步,无以至千里 1620

最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版

Part-E1-SDIO-Specification-Ver4.00-Final-120220.pdf:最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版,包括SDIO 接口的外设,SDIO 接口官方协议等。

leetcode 338 Counting Bits【leetcode新题】 数11,C++

leetcode 338 Counting Bits【leetcode新题】 数11,C++

编程小白小卿的博客 534

LeetCode - 338. Counting Bits

解题代码: classSolution { public:     vector countBits(int num) {         vector result(num+1);         result[0]=0;         for(int i=1;i             int j=i^(i-1);             if(j==1){        

u014642924的博客 235

leetcode 338:Counting Bits 数1,C++

题目: 刚刚写了一篇有分析的,然而。。。。上传失败,我的小心灵很受伤,决定直接发代码.....有空再写完整版的分析.....简单来说,就是 一个数X的1的个数(countBit(X)),满足 countBit(X)=countBit(2^N)+countBit(X-2^N),用迭代,复杂度O(n) class Solution { public:     vector countB

编程小白小卿的博客 333

Leetcode Algorithms - Dynamic Programming:338. Counting Bits

Description Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1’s in their binary representation and return them as an array. Example: For n...

weixin_38213125的博客 132

leetcode 338 : Counting Bits :找规律&位运算

338. Counting Bits My Submissions Question Total Accepted: 3211 Total Submissions: 5600 Difficulty: Medium Given a non negative integer number num. For every numbers i in the range

smileyk的专栏 447

动态规划

动态规划 最长连续子数列和 -2 6 -1 5 4 -7 2 3 求连续的子数列最大和。 根据递归的思路想:f(n) = max{ f(n-1) + num[n], num[n] } hdu1506Largest Rectangle in a Histogram 对于每一个高度h[i],搜索它能到达的最左,和最右,...

swallowblank的博客 184

leetcode刷题记录_动态规划_I

leetcode_62_unique path 动态规划: 声明二维数组,首行首列初始化为1,之后元素=上方值+左方值 level: simple 63. Unique Paths II //每一行/列的值与前一个状态有关,与uniquePath_I初始化不同 for(i=1;i<m;i++){//为第一列元素赋值 if(obstacleGrid[i][0] == 0){...

weixin_43276913的博客 173

leetcode【dynamic】【1】

338.Counting Bits 当前数二进制末位如果是1,加上一次,整体向右移动一位后,新的值是当前数的1/2,它已经被求过了,直接加上去就好了。 343.Integer Break 常规操作存在一种欠考虑的地方,下次自己要先跑两测试再run。 On的方法是:n>4的情况下,3^n是最大的,所以每次抽离3出来乘。 96.Unique Binary Search ...

weixin_30894389的博客 74

从‘An Easy Problem’看二进制位操作的实战技巧:如何优雅地找到下一个‘1’数量相同的数

本文深入探讨了如何通过二进制位操作高效寻找比给定整数大的最小数字,且其二进制表示中1的数量与原数相同。从暴力枚举法到位操作优化策略,详细分析了算法的时间复杂度与性能对比,并提供了多语言实现和实际应用场景,帮助开发者掌握这一信息学奥赛中的经典技巧。

weixin_30493401的博客 399

AI全栈实战 | 3.9-01 爬虫入门:requests 加 BeautifulSoup 三分钟跑通,但 90% 的人栽在这 4 个“礼貌“问题上

⚠️:本文内容仅用于。请遵守目标站点的服务条款与相关法律法规,不得对目标服务造成负担,不得采集、传播个人隐私数据。技术是中性的,边界在你手里。爬虫的入门技术(requests 发请求 + BeautifulSoup 解析)三分钟就能学会。真正区分"会用爬虫"和"会做爬虫的人"的,是这篇我们跑通"请求→解析→存储"的最小闭环,然后重点把"合规与礼貌"这根弦给你绷上。

源码获取 | 运行部署 | 定制二开修改,如果回复不及时请耐心等待,请见谅。 408
上一篇: 61. Rotate List【M】【54】【leetcode】
下一篇: 203. Remove Linked List Elements【E】【70】【leetcode】
Vicky_Vicky_990121
博客等级 码龄14年 23粉丝 187原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值