上后谈爱情

导航

 

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        }

 

 

posted on 2017-03-26 16:23  上后谈爱情  阅读(272)  评论(0编辑  收藏  举报