通过数学归纳方法总结规律,可以类比得出这样的公式(可参考百位类比): alt

class Solution {
public:
    int NumberOf1Between1AndN_Solution(int n) {
        int res = 0;
        long long multik = 1;
        for (int k = 0; n >= multik; k++) { /* multik代表10^k */
            long long multikTmp = multik * 10; /* 10^(k + 1) */
            res += ((n / multikTmp) * multik) + min(max((n % multikTmp) - multik + 1, 0LL), multik); /* 注意0LL */
            multik *= 10;
        }
        return res;
    }
};