求從1到n整數中1出現的次數:O(logn)演算法
阿新 • • 發佈:2019-01-10
劍指offer上的一題,但是感覺這位兄弟的解法更好
#include<iostream>
using namespace std;
#define N 2000
int cnt(int n)
{
if (n < 1)
{
return 0;
}
int count = 0;
int base = 1;
int 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;
}
int main()
{
int n;
cin >> n;
cout << cnt(n) << endl;
return 0;
}