题意链接
给定一个数n,求1到n这些数中1出现的次数。
问题分析
动规
有点难,问题转化为每一个位出现的次数。
其他
链接
class Solution {
public:
int countDigitOne(int n) {
long long i = 1, coef = 1, sum = 0, cur_sum = 0;
if (n < 10) return 1;
while(coef <= n) {
cout << n << endl;
//cout << "n coef " << n << '\t' << coef << endl;
//cout << (n / (coef * 10)) * coef << endl;
//cout << max(n % (coef * 10) - coef, 0) << endl;
sum += (n / (coef * 10)) * coef + min(max(n % (coef * 10) - coef+1, 0LL), coef);
//cur=n % 10;
coef = coef * 10;
//cout << "sum " << sum << endl;
}
return sum;
}
};