一、算是一种暴力求解法
int countNum(int n)
{
int count = 0;
while (n)
{
if (n % 10 == 1)++count;
n /= 10;
}
return count;
}
int GetNumberOf1(int n)
{
if (n <= 0)return 0;
int count = 0;
for (int i = 1;i <= n;++i)
count += countNum(i);
return count;
}
int main(int argc, char* argv[])
{
int num[10] = { 1,9,10,12,16,20,50,66,99,101 };
for (auto n : num)
{
std::cout << GetNumberOf1(n) << " ";
}
std::cin.get();
return 0;
}
二、分析数据特征进行解题
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
int PowerBase10(unsigned int n)
{
int result = 1;
for (unsigned int i = 0;i < n;++i)
{
result *= 10;
}
return result;
}
int NumberOf1(const char* strN)
{
if (!strN || *strN < '0' || *strN>'9' || *strN == '0')
return 0;
int first = *strN - '0';//取得数字的最高位
unsigned int length = static_cast<unsigned int>(strlen(strN));//获取长度
if (length == 1 && first == 0)//如果只有一位且为0情况
return 0;
if (length == 1 && first > 0)//如果只有一位且不为0情况
return 1;
int countNum = 0;
if (first > 1)//当最高位大于1时,说明最高位为1的情况出现了10^(长度-1)次,eg:22222,则1xxxx出现了10000次
countNum = PowerBase10(length - 1) + first * (length - 1) * PowerBase10(length - 2) + NumberOf1(strN + 1);
else if (first == 1)//当最高位等于1时,最高位出现1的次数等于最高位后面的值,eg:12222,则1xxxx出现了2222次
countNum = atoi(strN + 1) + 1 + first * (length - 1) * PowerBase10(length - 2) + NumberOf1(strN + 1);
//上面加的第二部分为当前长度(当前位数)余下部分每一个最高位出现的情况,
//eg:22222中,最高位为2,所以可以分成两段为2223~12222,12223~22222,每
//一段中除最高位,先选择1位为1,其余部分可以从0-9这10个数取1,根据排列
//组合可得两个段出现1的次数为2*4*10^3=8000次,即=最高位*余下位长度*10^(长度-2)
//第三部分即递归后面余下数字(第一段)的情况 eg:22222分成两段(1~2222,2223~222222)
//中的1~2222部分,依次往下递归
return countNum;
}
int GetNumberOf1(int n)
{
if (n <= 0)return 0;
char strN[50];
sprintf(strN, "%d", n);
return NumberOf1(strN);
}
int main(int argc, char* argv[])
{
int num[10] = { 1,9,10,12,16,20,50,66,99,101 };
for (auto n : num)
{
std::cout << GetNumberOf1(n) << " ";
}
std::cin.get();
return 0;
}