1~n中整数中1出现的次数

#include<iostream>

using namespace std;

int count(int n)
{
	if (n < 1)
		return 0;
	int base = 1;
	int count = 0;
	int round = n;
	while (round)
	{
		int weight = round % 10;
		round /= 10;
		count += base * round;
		if (weight == 1)
			count += (n%base) + 1;
		else if (weight > 1)
			count += base;
		base *= 10;
	}
	return count;
}

int main()
{
	int n = 214;
	printf("%d\n",count(n));

	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_39916039/article/details/82769358