剑指offer刷题————从1到整数n中1出现的次数

问题重述:

题目:输入一个整数n,求从1到n这n个整数的十进制表示中1出现的次数。例如输入12,从1到12着些整数中包含1的数字有1,10,11,12,1一共出现了5次(11中有两个1).

思路解析:

这道题的解析下面网址给出的解析非常简单明了,大家可以参阅。

https://leetcode-cn.com/problems/1nzheng-shu-zhong-1chu-xian-de-ci-shu-lcof/solution/mian-shi-ti-43-1n-zheng-shu-zhong-1-chu-xian-de-2/

代码实现:

class Solution {
public:
    int NumberOf1Between1AndN_Solution(int n)
    {
        int cur= 0;
        int high = 0;
        int low = 0;
        int res = 0;
        for(int i =1;i<=n;i*=10)
        {    
            cur=(n%(i*10))/i;
             high=n/(i*10);
            if(i==1)
                 low=0;
            else
                low =n%i;//cur为个位
            if(cur==0)
                res+=high*i;
            else if(cur==1)
                res+=high*i+low+1;
            else
                res+=(high+1)*i;
        }
        return res;
    }
};

 

你可能感兴趣的:(刷题)