題目:
輸入一個(gè)整數(shù)n掷邦,求從1到n這n個(gè)整數(shù)的十進(jìn)制表示中1出現(xiàn)的次數(shù)钞钙。
解法:
int numberOf1Between1AndN(int n) {
if (n <= 0) return 0;
char strN[50];
sprintf(strN, "%d", n);
return numberOf1(strN);
}
int numberOf1(const char* strN) {
int first = *strN - '0';
unsigned int length = static_cast<unsigned int>(strlen(strN));
if (length == 1 && first == 0) return 0;
if (length == 1 && first > 0) return 1;
int numFirstDight = 0;
if (first > 1)
numFirstDigit = PowerBase10(length - 1);
else if (first == 1) {
numFirstDigit = atoi(strN+1) + 1;
}
int numOtherDigits = first * powerBase10(length-2);
int numRecursive = numberOf1(strN + 1);
return numFirstDigit + numOtherDigits + numRecursive;
}