Leetcode Number of Digit One ,本算法主要使用递归的方法完成问题解决,相关代码及测试如下:
#include<iostream>
/*
* We use the recursive algorithm to solve this proble. We can conclued that
* the number with more digits can be construct by the less.
*/
using namespace std;
class solution {
public:
int countdigitone(int n) {
if (n <= 0) {
return 0;
}
if (n < 10) {
return 1;
}
int tmp = n;
int divide = 1;
int sum = 0;
int count = 0;
while (tmp / 10 > 0) {
count = count * 10 + divide;
divide *= 10;
tmp /= 10;
}
sum = (n / divide) * count;
// For the condition no more than 1**
if (n / divide > 1) {
sum += divide;
} else {
sum += n - divide + 1;
}
sum += countDigitOne(n % divide);
return sum;
}
};
// Sample input: ./a.out argv1
int main(int argc, char* argv[]) {
Solution so;
int re = so.countDigitOne(atoi(argv[1]));
cout<<"result: "<<re<<endl;
return 0;
}