码迷,mamicode.com
首页 > 其他好文 > 详细

【剑指offer】43、1~n整数中1出现的次数

时间:2018-07-21 17:15:20      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:int   turn   weight   思路   表示   code   else   color   alt   

题目

输入一个整数,求1~n的整数十进制表示中1出现的次数。如12,有1,10,11,12,总共出现了5次。

思路

注意不是统计出现1的数字的多少,而是统计1出现了几次。

我们按位来分析

个位:

技术分享图片

如果weight=0,则个位出现1的次数 = round

如果weight>=1,则个位出现1的次数=round + 1

 

十位:

技术分享图片

如果weight=0,则次数 = round * base

如果weight=1,则次数 = round * base + former + 1  ( former = n % base )

如果weight>1,则次数 = round * base + base

 

百位:和十位一样

 

例如534 = 个位 + 十位 + 百位 = (53*1 +1) + (5*10+10) + (0*100 + 100) =214

 2105 = (210*1+1) + (21*10) + (2*100+ 2105%100 + 1) + (0*1000 + 1000) = 3517

class Solution {
public:
    int NumberOf1Between1AndN_Solution(int n)
    {
        if(n < 1)
            return 0;
        int count = 0, base = 1, round = n;
        while(round > 0){
            int weight = round % 10;
            round /= 10;
            count += round*base;
            if(weight == 1)
                count += (n%base) + 1;
            else if(weight > 1)
                count += base;
            base *= 10;
        }
        return count;
    }
};

 

【剑指offer】43、1~n整数中1出现的次数

标签:int   turn   weight   思路   表示   code   else   color   alt   

原文地址:https://www.cnblogs.com/shiganquan/p/9346436.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!