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) {
            if (1 == (n%10))
                count++;
            n /= 10;
        }
        return count;
    }
    
    int NumberOf1Between1AndN_Solution(int n)
    {
        int res = 0;
        for (int i = 1; i <= n; i++) {
            res = res + numberOf1(i);
        }
        
        return res;
    }
};
原文地址:https://www.cnblogs.com/hesper/p/10579170.html