题目大意:求1~n个数中 2的个数
#include <iostream>
#include <cmath>
using namespace std;
int countAtSomeDigit(int num, int d) //0到num之间,第d位2的个数
{
int powerOf10 = (int)pow(10.0, d);
int nextPower = powerOf10 * 10;
int right = num % powerOf10;
int roundDown = num - num % nextPower;
int roundUp = roundDown + nextPower;
int digit = num / powerOf10 % 10;
if (digit < 2)
{
return roundDown / 10;
}
else if (digit == 2)
{
return roundDown / 10 + right + 1;
}
else
{
return roundUp / 10;
}
}
int count2s(int num) //0到num之间2的个数
{
int len = 0;
int temp = num;
while (temp)
{
len++;
temp /= 10;
}
int count = 0;
for (int i = 0; i < len; i++)
{
count += countAtSomeDigit(num, i);
}
return count;
}
int main()
{
cout << count2s(22)-count2s(0) << endl;
return 0;
}