给定一个十进制整数N,求出从1到N的所有整数中出现”1”的个数

//给定一个十进制整数N,求出从1到N的所有整数中出现”1”的个数。
int cal_num_of_1(int n)
{
	int count = 0;
	int temp;
	for (int i = 1; i<n+1; i++)
	{
		temp = i;
		while (temp>0)
		{
			if (temp%10 == 1)
			{
				count++;
			}
			temp = temp/10;
		}
	}

	return count;
}

int cal_num_of_1_2(int n)
{
	//1的个数
	int count = 0;
	//当前位
	int factor = 1;
	//低位数字
	int lower_num = 0;
	//当前位数字
	int cur_num = 0;
	//高位数字
	int higher_num = 0;

	if (n<=0)
	{
		return 0;
	}
	while (0 != n/factor)
	{
		//低位数字
		lower_num = n-(n/factor)*factor;
		//当前位数字
		cur_num = (n/factor)%10;
		//高位数字
		higher_num = n/(factor*10);

		switch (cur_num)
		{
		case 0:
			count += higher_num*factor; //如果为0,出现1的次数由高位决定:等于高位数字 * 当前位数
			break;
		case 1:
			count += higher_num*factor + lower_num + 1;//如果为1,出现1的次数由高位和低位决定:高位数字 * 当前位数 + 低位数字 + 1
			break;
		default:
			count += higher_num*factor + factor; //如果大于1,出现1的次数由高位决定:(高位数字+1)* 当前位数
			break;
		}
		factor *= 10; //前移一位

	}

	return count;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值