从1到N整数中1出现的次数

输入一个整数n,求从1 到n 这n 个整数的十进制表示中1 出现的次数 题目: 输入一个整数n,求从1 到n 这n 个整数的十进制表示中1 出现的次数。 例如输入12,从1 到12 这些整数中包含1 的数字有1,10,11 和12,1 一共出现了5 次。 解法: 这是一道比较经典的题目,编程之美上有递归和非递归两种解法(亦可参看http://blog.youkuaiyun.com/yuucyf/article/details/6698077) 这 阅读详情
题目:
输入一个整数n,求从1到n这n个整数的十进制表示中1出现的次数。例如输入12,从1到12这些整数中包含1的数字有1,10,11,12,1一共出现了5次。
一、暴力求解,不被推荐
class Solution
{
public:
    int NumberOf1Between1AndN( unsigned int n )
    {
        int number = 0;
        for ( int i = 0; i <= n; i++ )
        {
            number += NumberOf1( i );
        }
        return number;
    }
    int NumberOf1( unsigned int n )
    {
        int number = 0;
        while ( n )
        {
            if ( n % 10 == 1 )
                number++;
            n = n / 10;
        }
        return number;
    }
};
二、从数字规律着手解决
class Solution
{
public:
    int NumberOf1Between1AndN( int n )
    {
        if ( n <= 0 )
            return 0;
        char strN[50];
        sprintf( strN, "%d", n );
        return NumberOf1( strN );
    }

    int NumberOf1( const char *strN )
    {
        if ( !strN || *strN < '0' || *strN > '9' || *strN == '\0' )
            return 0;
        int first = *strN - '0';
        unsigned int length = static_cast<unsigned int>( strlen( strN ) );

        if ( length == 1 && first == 0 )
            return 0;
        if ( length == 1 && first > 0 )
            return 1;

        int numFirstDigit = 0;
        if ( first > 1 )
            numFirstDigit = PowerBase10( length-1 );
        else if ( first == 1 )
            numFirstDigit = atoi( strN+1 ) + 1;

        int numOtherDigits = first * ( length-1 ) * PowerBase10( length-2 ); //有些疑惑
        int numRecursive = NumberOf1( strN+1 );
        return numFirstDigit+numOtherDigits+numRecursive;
    }

    int PowerBase10( unsigned int n )
    {
        int result = 1;
        for ( unsigned int i = 0; i < n; ++i )
            result *= 10;
        return result;
    }
};
SpringBoot+Vue前后端分离项目实战:个人博客系统 MyBlog主要是基于 SpringBoot + Vue 前后端分离开发的一款动态个人博客系统,后台和前台均通过JSON数据做交互,主要功能有文章管理、分类管理、标签管理、附件管理、评论管理、友链管理、个人资料/博客信息管理等。 阅读详情

相关推荐

UDS诊断入门第一课:手把手教你玩转0x10会话控制服务(附ISO14229实战解析)

刚接触汽车电子诊断的工程师们,往往会被厚厚的ISO 14229标准文档和各种专业术语吓退。但就像学习编程要从"Hello World"开始一样,掌握UDS协议的最佳切入点就是0x10诊断会话控制服务。这个看似简单的服务,实际上是整个诊断系统的"钥匙"——它决定了ECU(电子控制单元)当前处于何种工作模式,直接影响着其他诊断服务的可用性。 在实际车辆诊断中,ECU默认处于DefaultSession模式,这种模式下许多高级诊断功能是被禁用的。想象一下你正在开发一个需要刷写ECU固件的工具,如果连最基本的会

weixin_30402343的博客 394

算法—从1到n整数中1出现的次数

题目 求出113的整数中1出现的次数,并算出1001300的整数中1出现的次数?为此他特别数了一下1~13中包含1的数字有1、10、11、12、13因此共出现6次,但是对于后面问题他就没辙了。ACMer希望你们帮帮他,并把问题更加普遍化,可以很快的求出任意非负整数区间中1出现的次数(从1 到 n 中1出现的次数)。 分析 借鉴牛客上面Duqcqid大神的题解 这道题需要归纳分析,按照位,求出1可能出现的次数,再把每位上1出现的次数相加即可。 个位上1可能出现的次数 + 十位上1可能出现的次数 + 百位上1可

shengpeizhu的博客 877

智能座舱语音测试避坑指南:从唤醒率到方言识别,这些场景你测全了吗?

本文深入解析智能座舱语音测试的关键场景与避坑指南,涵盖唤醒率测试、方言识别、多音区交互等复杂场景。通过实战案例与自动化测试方案,帮助开发者全面提升语音系统的可靠性与用户体验,特别关注环境噪声干扰与方言覆盖策略。

weixin_42613501的博客 498

从1到n整数中1出现的次数:O(logn)算法

1. 题目描述输入一个整数n,求从1到n这n个整数的十进制表示中1出现的次数。例如输入12,从1到12这些整数中包含1的数字有1,10,11和12,1一共出现了5次。2. 题目来源第一次看到是在《剑指Offer》第2版上,leetcode和牛客网上都有这道题。3. 本片博客的目的看了《剑指Offer》上的解法,我觉得不能算好: 这段解释描述有些不清晰,而且没有图,难以理解。 从书中给出的实现上来看,

yi_Afly的专栏 2万+

SAP-ABAP:SAP ABAP 深度解析:BAPI 从入门到精通 —— 原理、实战与自定义开发全指南

SAP ABAP BAPI 深度解析摘要 本文全面介绍了 SAP ABAP 中的 BAPI(业务应用程序编程接口)技术,涵盖以下核心内容: BAPI 定义与特点:BAPI 是 SAP 为业务对象提供的标准化编程接口,具有面向对象、封装业务逻辑、标准化错误处理和版本兼容性等特点。 BAPI 与 RFC 关系:所有 BAPI 都是 RFC,但需额外满足业务对象注册、标准化参数和错误处理等要求。 BAPI 核心作用:包括业务逻辑封装、系统集成、标准化错误处理、版本兼容和审计合规。 实战演示:通过创建销售订单的完整

baidu_35680696的博客 1034

高温环境下(100℃以上)相机的几种保障方案

高温环境下相机保障措施摘要:针对120℃以上高温环境,相机需采取多重防护:1.散热设计采用金属机身、散热鳍片或风扇;2.关键部件选用耐高温材料(铝合金、特种玻璃);3.电子元件需军规级芯片并做三防处理;4.建议外接电源或耐高温电池。工业相机(如FLIR A655sc、Basler ace)及特种机型(Ximea xiQ)具备高温适应性,普通相机可加装隔热套件配合冷却系统。选择时需关注传感器信噪比和全局快门性能,并设置温度监控保护机制。注意高温会加速设备老化,需定期检测维护。(149字)

start_up_go的博客 1589

1~n 整数中 1 出现的次数

题目描述 输入一个整数 n ,求1~n这n个整数的十进制表示中1出现的次数。 例如,输入12,1~12这些整数中包含1 的数字有1、10、11和12,1一共出现了5次。 示例 1: 输入:n = 1 输出:5 (分别是1 10 11 12) 示例 2: 输入:n = 13 输出:6 (分别是1 10 11 12 13) 思路 首先我们知道,肯定可以用求模取余的方法来获取1~n这n个数每个数位上的数,如果是1的话则ans+1,但我们有更巧妙的方法。 根据...

ThinPikachu的博客 3930

58.Sobel边缘检测算子

注:在梯度运算中,很可能会出现负的灰度值,我们不能再采用uint8类型作为像素的数据类型,而是采用了CV_16S或者CV_32F这种有负数范围的类型,运算结果里的负数也不能不处理,否则在显示的时候就会被截断为0,这样就会丢失边界信息。如下图所示,对中心像素Z5求取多个方向的灰度差分,对于Z5的8邻域,分为4个方向,即对角线和水平垂直4个方向对:(z1, z9) ,(z2, z8), (z3, z7), (z6, z4) 给定邻域方向梯度矢量g的幅度为:|g| = <像素灰度差分>/<相邻像素的距离>。

twnkie的博客 4884

算法学习之整数中1出现的次数(从1到n整数中1出现的次数)

题目描述 求出1~13的整数中1出现的次数,并算出100~1300的整数中1出现的次数?为此他特别数了一下1~13中包含1的数字有1、10、11、12、13因此共出现6次,但是对于后面问题他就没辙了。ACMer希望你们帮帮他,并把问题更加普遍化,可以很快的求出任意非负整数区间中1出现的次数(从1 到 n 中1出现的次数)。 那种简单的嵌套双遍历这里就不讲了,说一下另一种思路,使用归纳法总结...

qq_35523678的博客 1263

使用静态库在嵌入式系统中进行开发

静态库是一种包含预编译对象代码的文件,它可以与应用程序链接在一起,并在编译时将库的代码复制到最终的可执行文件中。静态库是包含预编译对象代码的文件,可以与应用程序链接在一起,并在编译时将库的代码复制到最终的可执行文件中。需要注意的是,由于嵌入式系统的资源限制,开发人员应该仔细选择需要包含在静态库中的功能,并避免引入不必要的依赖关系。需要注意的是,由于嵌入式系统的资源限制,开发人员应该仔细选择需要包含在静态库中的功能,并避免引入不必要的依赖关系。的静态库文件,可以在嵌入式系统的应用程序中使用它了。

ZrElixir的博客 205

分享一个我自用的 Python 消息发送模块,支持邮件、钉钉、企业微信

🔥 分享一个我自用的 Python 消息发送模块,支持邮件、钉钉、企业微信

XiaoqiangClub的博客 478

从1到n整数中1出现的次数

题目描述: 输入一个整数n,求从1到n这n个整数的十进制表示中1出现的次数。 例如输入12,从1到12这些整数中包含“1”的数字有1,10,11和12,其中“1”一共出现了5次。 样例: 输入: 13 输出: 6 解释: 数字 1 出现在以下数字中: 1, 10, 11, 12, 13 。 分析: 首先先看数字n是几位数,记为len。 第二步取出n最高位的数字,判断该数字和1的关系,计算最高位1出...

hahaEverybody的博客 421

华为OD机试双机位C卷-虚拟文件系统(C/C++/Py/Java/Js/Go)

华为OD机试(机考)双机位C卷 【虚拟文件系统】,提供C语言、Java、C++、Python、Go、JavaScript源码实现,并提供完整思路讲解,以及在线OJ模拟做题。华为OD机试真题【虚拟文件系统】。

qq_45776114的博客 479

整数中1出现的次数(从1到n整数中1出现的次数)

题目描述 求出113的整数中1出现的次数,并算出1001300的整数中1出现的次数?为此他特别数了一下1~13中包含1的数字有1、10、11、12、13因此共出现6次,但是对于后面问题他就没辙了。ACMer希望你们帮帮他,并把问题更加普遍化,可以很快的求出任意非负整数区间中1出现的次数(从1 到 n 中1出现的次数)。 方法一 最简单的方法就是遍历区间内所有的数中1的个数… public int...

如是说的博客 1186

ssm框架搭建

这个是一个在idea上成功跑起来的ssm框架项目,保存在这里方便以后使用直接下载

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

计算整数n的所有因子之和_算法系列之从1到n整数中1出现的次数

题目来源 剑指offer01 题目输入一个整数n,求从1到n,这n个十进制整数1出现的次数。例如,12, 那么1到12中包含1的数字有{1,10,11,12},其中11包含两个1,故总共5个数。02 解法1看到这道题,我们的第一反应很容易想到,从1遍历到n,然后计算每个数中1的个数。我们分析一下时间复杂度,从1到n遍历这个值的时间消耗是 o(n)。计算每个数中的1的个数花费的时间是log(n)。l...

weixin_33374585的博客 1871

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

1-n整数中1出现的次数

题目 输入一个整数n,求1-n这n个整数的十进制表示中1出现的次数。 例如 输入12 这些整数中包含1的整数有1,10,11,12。1一共出现了5次。 思路 思路一 暴力解法。遍历从1到n的n个整数,并且每个整数挨个检查每一位是否是1.时间复杂度太高。 思路二 使用递归的思想。 例如输入的整数为21345. 把其分为1-1345和1346-21345两部分求解。 先看134...

weixin_42518668的博客 463

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

剑指Offer-31.整数中1出现的次数(从1到n整数中1出现的次数)(Javascript)

31.整数中1出现的次数(从1到n整数中1出现的次数) 《剑指Offer》刷题GitHub链接 题目链接 题目描述 求出1 ~ 13的整数中1出现的次数,并算出100 ~ 1300的整数中1出现的次数?为此他特别数了一下1~13中包含1的数字有1、10、11、12、13因此共出现6次,但是对于后面问题他就没辙了。ACMer希望你们帮帮他,并把问题更加普遍化,可以很快的求出任意非负整数区间中1出现的...

沐沐 831

整数中1出现的次数(从1到n整数中1出现的次数)(C++)

  输入一个整数 n ,求 1~n 这 n 个整数的十进制表示中 1 出现的次数   例如, 1~13 中包含 1 的数字有 1 、 10 、 11 、 12 、 13 因此共出现 6 次注意:11 这种情况算两次数据范围:1≤n≤30000进阶:空间复杂度 O(1),时间复杂度 O(lognn) 示例2 思路/解法 方式一 方式二......

田螺姑娘的博客 2467

1到n整数中1出现的次数

1到n整数中1出现的次数 题目描述 输入一个整数n, 求1~n这n个整数的十进制表示中1出现的次数. 例如, 输入12, 1~12这些整数中包含1的数字有1, 10, 11和12, 1一共出现了4次 class Solution { public: int numberOf1(int n) { int count = 0; while (n) ...

weixin_30568591的博客 107

统计在从1到n的正整数中1出现的次数

统计在从1到n的正整数中1出现的次数 1、最直观的想法,求1到n中每个整数中1出现的次数,然后相加即可。而求每个十进制整数中1出现的次数,我们先判断这个数的个位数是否是1,如果这个数大于10,除以10之后再判断个位数是否为1,循环直至求出该整数包含1的个数。 代码如下: #include "stdafx.h" #include "stdlib.h" #include #include

dazhong159的专栏 1万+

java之从1到n整数中1出现的次数

题目:输入一个整数n,求从1到n个整数的十进制表示中1出现的次数。例如输入12,从1到12这些整数中包含1的数字有1、10、11和12、1一共出现5次。 解法1: package BitCount; import java.util.Scanner; public class CountOneMain { public static int countOne(int n) { in

qq_27291877的博客 622
上一篇: 连续子数组的最大和
下一篇: 把数组排成最小的数
Findway_
博客等级 码龄10年 36粉丝 117原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值