【第十五届蓝桥杯C/C++大学b组省赛】2024试题 C:好数 本人想法&答案

这道题是简单难度,只需要跟着题目要求走,进行相应判断就好,没有卡数据。

#include<algorithm>
#include<iostream>
#include<vector>
#include<cmath>
#include<cstring>
#include<stdio.h>
#include<string>
#include<math.h>

using namespace std;

// 功能:判断数字 x 是否是好数
bool ishaoshu(long long x) {
    int digit;
    int pos = 0;  // 用于标记当前位的位置(从0开始计数)

    while (x > 0) {
        digit = x % 10;  // 获取当前最低位的数字
        x /= 10;         // 移除当前最低位

        // 奇数位置上的数字必须是奇数,偶数位置上的数字必须是偶数
        if (pos % 2 == 0) {
            // 个位、百位、万位... (奇数位置)
            if (digit % 2 == 0) return false;
        } else {
            // 十位、千位、十万位... (偶数位置)
            if (digit % 2 != 0) return false;
        }

        pos++;  // 移动到下一位
    }

    return true;  // 如果所有位都符合条件,则是好数
}

int main() {
    long long n;
    cin >> n;

    int count = 0;
    for (long long i = 1; i <= n; i++) {
        if (ishaoshu(i)) {
            count++;
        }
    }

    cout << count << endl;  // 输出好数的总数
    return 0;
}

By the way,如果考试里忘了那个把数字每个位拆分的while怎么写,可以考虑狠活:

#include <algorithm>
#include <iostream>
#include <cmath>
#include <cstring>
#include <vector>

using namespace std;

int getu(int *a)
{
	int i;
	for(i=8;i>=0;i--)
	{
		if(a[i]!=0)
		{
			return i;
		}
	}
}

bool ishaoshu(long long x){
	int a[9],i,t = 0;
	a[0] = x % 10;
	a[1] = (x % 100 - a[0]) / 10;
	a[2] = (x % 1000 - a[0] - a[1]*10) / 100;
	a[3] = (x % 10000 - a[0] - a[1]*10 - a[2]*100) / 1000;
	a[4] = (x % 100000 - a[0] - a[1]*10 - a[2]*100 - a[3]*1000) / 10000;
	a[5] = (x % 1000000 - a[0] - a[1]*10 - a[2]*100 - a[3]*1000 -a[4]*10000) / 100000;
	a[6] = (x % 10000000 - a[0] - a[1]*10 - a[2]*100 - a[3]*1000 -a[4]*10000 -a[5]*100000) / 1000000;
	a[7] = (x % 100000000 - a[0] - a[1]*10 - a[2]*100 - a[3]*1000 -a[4]*10000 -a[5]*100000 - a[6]*1000000) / 10000000;
	a[8] = (x % 1000000000 - a[0] - a[1]*10 - a[2]*100 - a[3]*1000 -a[4]*10000 -a[5]*100000 - a[6]*1000000 -a[7]*10000000) / 100000000;
    t = getu(a);
	for(i=0;i<=t;i++)
	{
		
		if(i == 8 || i == 6 || i == 4 || i == 2 || i == 0)
		{
			if(a[i]%2 == 0 )
			{
				return false;
			}
		}
		if(i == 1 || i == 3 || i == 5 || i == 7)
		{
			if(a[i]%2 == 1)
			{
				return false;
			}
		}
	}
return true;
}

int main(){
	
	long long a,count=0,i,n,t = 1234;
	cin >> n;
	
	
	for(i=1;i<=n;i++)
	{
		if(ishaoshu(i))
		{
			count++;
		}
	}
	
	printf("%lld",count);
} 

过掉了,但是还有个好方法就是把所有好数列出来,同志们可自行编写。。。。。。

  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值