CCF-201912-1(报数)

本文介绍两种使用C++实现的算法,用于计算在1到n范围内,排除所有包含数字7或为7的倍数的整数后,剩余数字的分布情况。通过数组记录每四数一轮的跳过个数,以及利用模运算判断是否为7的倍数或含有7,确保了算法的高效性。

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

一:问题
在这里插入图片描述
在这里插入图片描述

二:理解
1.用一个数组jump[4];来存储跳过的个数。
2.用realn,和num来计算不跳过的个数和数字的个数;
判断num是不是7的倍数,或者num中是不是含有7;

while(temp2 != 0)
{
	temp1 = temp2%10;
	temp2 /= 10;
	if(temp1 == 7)
		break;
}
if(temp1==7 || num%7==0)
{
	jump[num%4]++;
	num++;
	continue;
}

3.jump[num%4]分别记录的是:
jump[1] 存储第一个数
jump[2] 存储第二个数
jump[3] 存储第三个数
jump[0] 存储第四个数

三:代码

#include<bits/stdc++.h>
#include<iostream>
using namespace std;

int main()
{
	int n;
	cin >> n;
	int num = 1;
	int realn = 1;
	int jump[4] = {0};
	while(realn <= n)
	{
		int temp1 = 0;
		int temp2 = num;
		while(temp2 != 0)
		{
			temp1 = temp2%10;
			temp2 /= 10;
			if(temp1 == 7)
				break;
		}
		if(temp1==7 || num%7==0)
		{
			jump[num%4]++;
			num++;
			continue;
		}
		num++;
		realn++;
	}
	for(int i=1; i<4; i++)
		cout << jump[i] << endl;
	cout << jump[0] << endl;
	return 0;
}

第二个代码:

#include<bits/stdc++.h>
#include<iostream>
#include<algorithm>
using namespace std;

int num[4] = {0};
int counts = 0;

int main()
{
	int n;
	cin >> n;
	int i = 1;
	while(1)
	{
		if(!(i%7))  //是7的倍数 
			num[(i-1)%4]++;
		else
		{
			int temp = i;
			int a;
			while(temp)
			{
				a = temp%10;
				if(a == 7)
					break;		
				temp /= 10;	
			}
			if(a==7)
				num[(i-1)%4]++;
			else
				counts++;
		} 
		if(counts == n)
			break;
		i++;
	}
	for(int i=0; i<4; i++)	
		cout << num[i] << endl;
	return 0;
} 

感觉这个题目的数据有个坑,说的小于666,所以我只判断了个位与十位。结果提交只有60。
感觉这次的代码手感比上次的好。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值