第二十二题 从1到n的正数中1出现的次数

本文介绍了一个计算从1到给定整数N中数字1出现总次数的算法。通过将整数转换为字符串并分段计算,有效地解决了问题。文章提供了完整的C++实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:输入一个整数n,求从1nn个整数的十进制表示中1出现的次数。

例如输入12,从112这些整数中包含的数字有11011121一共出现了5次。

#include "string.h"
#include "stdlib.h"
#include <iostream>
int NumberOf1(const char* strN);
int PowerBase10(unsigned int n);
using namespace std;
//求取1的个数
int NumberOf1BeforeBetween1AndN_Solution2(int n)
{
	if(n <= 0)
		return 0;

	// convert the integer into a string
	char strN[50];
	sprintf(strN, "%d", n);

	return NumberOf1(strN);
}
//将int转为string后,分别求取最高位的1的个数和除了最高位之外的1的个数
//21345分为1-1345,1346-21345
int NumberOf1(const char* strN)
{
	if(!strN || *strN < '0' || *strN > '9' || *strN == '\0')
		return 0;

	int firstDigit = *strN - '0';
	unsigned int length = static_cast<unsigned int>(strlen(strN));

	// the integer contains only one digit
	if(length == 1 && firstDigit == 0)
		return 0;

	if(length == 1 && firstDigit > 0)
		return 1;

	//最高位的1的个数
	int numFirstDigit = 0;
	//除了最高位外其他位1的个数
	int numOtherDigits = firstDigit * (length - 1) * PowerBase10(length - 2);
	// numRecursive is the number of 1 of integer 1345
	int numRecursive = NumberOf1(strN + 1);

	//当最高位大于1时最高位1的个数
	if(firstDigit > 1)
		numFirstDigit = PowerBase10(length - 1);

	//当最高位=于1时最高位1的个数
	else if(firstDigit == 1)
		numFirstDigit = atoi(strN + 1) + 1;

	return numFirstDigit + numOtherDigits + numRecursive;
}
int PowerBase10(unsigned int n)
{
	int result = 1;
	for(unsigned int i = 0; i < n; ++ i)
		result *= 10;

	return result;
}
int main()
{
	cout<<NumberOf1BeforeBetween1AndN_Solution2(21345);
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值