zoukankan      html  css  js  c++  java
  • 1到N上计算其中1出现次数

    1.剑指offer : 出现一道题:计算1到N上1出现的次数,实在无法看懂其中的编程思想,现在参考:

    http://blog.csdn.net/yi_afly/article/details/52012593。从中得出一些想法,对此中想法总结。

    2.解题思路:将N的十进制中的位数一步步取出来进行分析:

    1)个位:从1到N,每增加1,weight+1,当weight从0-9 会重复周期循坏,对于这种轮回出现次数取决于N的高位 这里讲高位用round表示:

        对于下面534 : 出现轮回次数 53次   weight从 0-9 ,此时base=1;

        对于weight >0: 第54次轮回中1有重新出现一次: 总共出现次数 Round*base+1;

    2). 十位:

         分析方法与个位一样,不同的是 个位每增加1 十位增加1,同时十位数是1时,个位0-9出现10次,base=10;

    则有 round*base=5*10;

     在来看weight值: 当weight>1时,第六轮出现1,个位代表10次 :round*base+base;

    weight=1:  n=514;看个位 如果个位数>=1只能 是增加1:    5*10+(个位+1)

    weight=0  : N=504   : 5*10;

    3) 对于更高位数还不是一样

    4)总结:

     当个位之言:

           若个位>0:1出现次数 round*1+1;

       若个位等于0: 1出现次数round*1;

    对于十位:base=10,百位base=100

    若 weight=0:round*base

    若 weight=1: round*base+foremer+1;

    weight>1:round*base+base:

     明显:计算取出的N位数计算,总的时间复杂度:lg(N)

     1  if(N<1)
     2                return 0;
     3            int count=0,round=N,base=1;
     4            
     5              while(round>0)
     6            {
     7                int weight=round%10;
     8                round=round/10;
     9                count+=round*base;
    10                if(weight==1)
    11                    count+=(N%base)+1;
    12                else if(weight>1)
    13                    count+=base;
    14                base=base*10;
    15            }
    16              return count;
    17        }

     

  • 相关阅读:
    作业
    作业
    [转]C语言指针 之 函数指针
    iOS 隐私政策
    微信小程序成长记录(一)
    ios 用信号量控制多个异步网络请求
    ios 利用cocapods创建私有库
    ios 整理获取设备相关信息
    ios_scrollView顶部图片下拉放大
    ios 在项目中使用文字ttf文件
  • 原文地址:https://www.cnblogs.com/woainifanfan/p/6623137.html
Copyright © 2011-2022 走看看