leetcode 338. Counting Bits

七天征服AutoSAR/SomeIP_01速成配置并代码生成 本文为AutoSAR中SomeIP配置开发的实操指南摘要,重点介绍通过通信矩阵快速构建SomeIP工程的方法。核心内容包括:1)基于Excel通信矩阵生成系统描述文件(arxml);2)在AutoSAR工具中导入文件自动生成协议栈配置,涵盖ETHIF、SoAd等模块;3)关键报错处理(COM/PDUR/SOAD/SD模块的配置修正);4)SomeIPXF的数据编解码配置;5)SWC组件与RTE任务映射。教程强调"先完成再完美"的实践原则,指导开发者快速生成基础代码框架,为后续协议调试奠定 阅读详情

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 1:

Input: 2
Output: [0,1,1]
Example 2:

Input: 5
Output: [0,1,1,2,1,2]

给出一个数num,让output出从0到num中所有整数的二进制数中有多少个1,返回数组

思路:
找规律
参考https://www.cnblogs.com/grandyang/p/5294255.html中的方法3

规律是,从1开始,遇到偶数时,其1的个数和该偶数除以2得到的数字的1的个数相同,遇到奇数时,其1的个数等于该奇数除以2得到的数字的1的个数再加1

   0000    0
-------------
   0001    1
-------------
   0010    1
   0011    2
-------------
   0100    1
   0101    2
   0110    2
   0111    3
-------------
   1000    1
   1001    2
   1010    2
   1011    3
   1100    2
   1101    3
   1110    3
   1111    4
//1ms
    public int[] countBits(int num) {
        
        int[] result = new int[num + 1];
        
        for (int i = 1; i <= num; i++) {
            if (i % 2 == 1) { //odd.. 
                result[i] = result[i / 2] + 1;
            } else {   //even..
                result[i] = result[i / 2];
            }
        }
        
        return result;
    }

方法二:
巧妙利用i & (i-1), 这是用来判断是否为2的指数的方法,为0时表示是2的指数,
用dp数组保存当前i bit为1的个数,dp[i] = dp[i & (i-1)] + 1

//1ms
    public int[] countBits(int num) {
        if(num < 0) {
            return new int[]{};
        }
        
        int[] dp = new int[num + 1];
        dp[0] = 0;
        
        for(int i = 1; i <= num; i++) {
            dp[i] = dp[i & (i - 1)] + 1;
        }
        
        return dp;
    }
手把手教你学simulink实例--基于Simulink的船舶动力装置性能评估与仿真 船舶动力装置是船舶运行的核心系统,其性能直接影响船舶的安全性、经济性和环保性。基于MATLAB/Simulink平台进行船舶动力装置性能评估与仿真是研究和优化船舶动力系统的重要手段。通过建模与仿真,可以分析动力装置在不同工况下的性能表现,并验证控制策略的有效性。本项目旨在构建一个完整的船舶动力装置性能评估与仿真模型,包括发动机建模、传动系统建模、负载分析以及性能评估模块,并通过仿真分析其动态响应和性能指标。 阅读详情

相关推荐

Andriod应用开发基础项目——记账本

本项目采用Java语言编写,是一款基于Android Studio开发的简易项目,本项目可以提高Java语言编写软件的能力,同时加深对开发软件Android studio有了更深层次的掌握,很适合初学者。在项目过程中,遇到了一些挑战和问题,但通过不断的努力和学习,最终取得了成功。未来,可以还可以继续优化App的功能和性能,增加更多实用的功能,提升用户体验。

eryasd的博客 3476

LeetCode 338. Counting Bits

338. Counting BitsGiven 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:

mingjc的博客 254

FPGA篮球计分器:从需求分析到模块化实现的实战指南

本文详细介绍了FPGA篮球计分器的设计与实现,涵盖需求分析、模块化设计及实战调试。重点解析了24秒精确倒计时、12分钟比赛计时、比分统计和数码管显示等核心模块的Verilog实现,提供了按键消抖、状态机设计和BCD码处理等关键技术细节,帮助开发者掌握FPGA数字系统设计方法。

sql99的博客 230

LeetCode 338. Counting Bits 题解

本题是位运算和动态规划的结合应用。利用位运算的性质动态规划状态转移时间复杂度 O(n)通过本题可以深入理解位运算的应用和动态规划的优化。

cannonjinx的博客 1760

量子城域网建设设备系列(三):网络管理系统(NMS)

本文对量子网络中的网络管理系统进行了初步的介绍。

量子领域相关话题 2030

RK3588部署rtmpose模型

摘要: 本文详细介绍了在RK3588开发板上部署RTMPose模型的全流程。首先在Ubuntu环境中搭建MMCV框架,通过MMPose工具将PTH模型转换为ONNX格式。随后使用RKNN-Toolkit2将ONNX模型转换为RKNN格式,并完成开发板部署。关键步骤包括模型转换(PTH→ONNX→RKNN)、环境配置和推理验证,最终实现人体姿态估计功能。整个过程涉及MMPose、RKNN-Toolkit等工具链的使用,为边缘计算场景下的实时姿态分析提供了可行方案。

qq_44224801的博客 1235

[leetcode]338. Counting Bits

[leetcode]338. Counting Bits Analysis 周五ummmmmm—— [啊啊啊啊 paper结果要出来了,心塞] Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1’s in ...

weixin_32135877的博客 164

6-2 GPU GART 绑定机制与 TLB 失效

本文详细解析了AMD GPU的GART(Graphics Address Remapping Table)绑定机制实现。主要内容包括: 绑定流程:从ttm_tt_bind()到硬件PTE更新的完整调用链,重点分析amdgpu_gart_bind()函数实现。 关键函数: amdgpu_gart_bind():执行安全检查、记录映射关系、更新页表等操作 amdgpu_gart_map():将CPU页映射为多个GPU页并填充PTE amdgpu_gmc_set_pte_pde():处理硬件特定的PTE格式 内存

图形/计算GPU的驱动与虚拟化技术分享园地 2695

leetcode 338 Counting Bits 详细解答

leetcode 338 Counting Bits 详细解答 以例子说明: Index :      0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 bin nums : 0 1 1 2 1 2 2 3 1 2 2  3    2   3   3   4   1

qq_22210659的博客 236

康耐视visionpro-CogBlobTool工具详细说明

康耐视visionpro-CogBlobTool工具详细说明

视觉人机器视觉的博客 1744

uniapp - [全端兼容] 高性能 tabbar 底部菜单凸起效果,原生系统自定义底部菜单不卡顿、切换页面不闪烁、自动缓存页面(底部菜单中间自定义一个图片并悬浮起来)

uniapp如何实现底部凸起按钮,uniapptabbar底部菜单怎么自定义,uniapp怎么让底部菜单中间突出来,uniapp自定义底部tabbar,uniapp高性能好用的底部菜单,uniapp自定义底部导航栏并解决闪烁问题,uniapp怎么设置凸起的底部tabbar,uniapp怎么用系统的底部菜单还想让中间的按钮凸起来,uniapp自定义tabbar性能不好怎么办,uni-app自定义导航栏实现中间凸起效果,uniapp底部导航栏中间圆形按钮凸起效果详细代码,uni-app自定义中间图标突起的

🏆 前端领域优质创作者 1万+

LeetCode-338. Counting Bits [C++][Java]

Given an integern, returnan arrayansof lengthn + 1such that for eachi(0 <= i <= n),ans[i]is thenumber of1'sin the binary representation ofi.

贫道绝缘子的博客 966

基于Scrapy+Playwright的学术会议信息智能爬取系统实战

本文详细介绍如何使用Python构建一个高效的学术会议信息爬取系统,结合Scrapy框架和Playwright无头浏览器技术,实现对全球学术会议数据的自动化采集、清洗和存储。文章包含完整的技术方案设计、代码实现细节以及性能优化策略,可帮助读者快速掌握现代网络爬虫开发的核心技术。关键词:Python爬虫、Scrapy、Playwright、学术会议、数据采集、反爬对抗python复制下载。

2201_76125261的博客 720

LeetCode-338. Counting Bits

LeetCode-338. Counting Bits 题目描述:https://leetcode.com/problems/counting-bits/ 解题思路 当然,如果逐位取模再判断是不是1来计算1的个数当然可以,但这样时间复杂度就是O(n*sizeof(integer)) 了,我们想要O(n) 就好。 所以,在于对给定的数num ,我们对区间0 ≤ i ≤ num中的每个数求1 的...

ke1950523491的博客 275

老版QQ原生表情gif动态

这是老版的QQ表情,不过全是动态的的,Windows照片查看器是不会动的,可以右击用浏览器打开查看,再说一遍是老版的,只是分享给宁愿用老版也要动态的人。

深度学习工具包 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")

Leetcode338. Counting Bits

计算二级制数中 1 的数目。

magic_jiayu的博客 219

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

LeetCode OJ-338.Counting Bits

LeetCode OJ-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 a

oYinGui1 594

visio安装包

Microsoft Office Visio 是一款专业的制图软件。利用经过更新的形状、协作工具和数据链接图表,创建专业级图表以简化复杂的信息。

[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 ar

Smaug的专栏 610

LeetCode 338.Counting Bits 解题报告

LeetCode 338.Counting Bits 解题报告

骆小坑的填坑之旅 580

LeetCode 338.Counting Bits 题解(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.

prayyojay的博客 335

【LeetCode】338Counting Bits

【链接】: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.Exa

herongwei 的 BLOG 606

Leetcode 338. Counting Bits (Medium) (cpp)

Leetcode 338. Counting Bits (Medium) (cpp)

还是需要多学习!闷声大发财,这是坠吼的! 876

[LeetCode]338. Counting Bits

[LeetCode]338. Counting Bits思路对于每一位数,计算其中1的个数,计算过程优化,可以使时间较短代码class Solution { public: vector<int> countBits(int num) { vector<int> res; for (int i = 0; i < num + 1; ++i) {

Lcharon的博客 3222

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的博客 461

LeetCode Top 100 Liked Questions 338. Counting Bits (Java版; Medium)

welcome to my blog LeetCode Top 100 Liked Questions 338. Counting Bits (Java版; Medium) 题目描述 Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number ...

littlehaes的博客 225

LeetCode中338Counting Bits的题解

题目来源是LeetCode中的338题,题干意思很简单,就是给出一个非零整数,要求计算该整数范围内的每一个数所对应的二进制位中“1”的数量,并将其存储在一个数组中,返回数组。题目在LeetCode中属于中等难度题,因为特地要求了时间复杂度和空间复杂度均为O(n),按照常规做法很容易得到所需要的输出结果,但是时空间复杂度达不到要求。这也是该题的关键所在,把这道题的解题思路整理如下。 一、原题描

codekiller_的博客 321

[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

TstsUgeg的博客 3386
上一篇: leetcode 322. Coin Change(交换硬币)
下一篇: leetcode 343. Integer Break(dp和math方法)
蓝羽飞鸟
博客等级 码龄8年 1万+粉丝 727原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

打赏作者

蓝羽飞鸟

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

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

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

打赏作者

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

抵扣说明:

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

余额充值
⌂ 换网址