PAT_甲级_1152 Google Recruitment (20point(s)) (C++)【字符串处理/寻找质数】

目录

1,题目描述

 题目大意

2,思路

3,AC代码

4,解题过程

第一搏

第二搏


1,题目描述

  • recruitment:招募,招聘;

Sample Input 1:

20 5
23654987725541023819

 

Sample Output 1:

49877

 

Sample Input 2:

10 3
2468024680

 

Sample Output 2:

404

 题目大意

给出一个字符串,找到字符串中第一个长度为K的质数(K个数连续),若不存在则输出404.

 

2,思路

每次从字符串s中截取长度为K的子字符串s1,将其转换为int型数字,并判断是否为质数,若是则将其补满K个数字输出(用0来补)。

 

3,AC代码

#include<bits/stdc++.h>
using namespace std;
int L, K;
bool isPrime(int x){
    if(x <= 1) return false;
    for(int i = 2; i <= sqrt(x); i++){
        if(x % i == 0)
            return false;
    }
    return true;
}
int main(){
#ifdef ONLINE_JUDGE
#else
    freopen("1.txt", "r", stdin);
#endif // ONLINE_JUDGE
    string s, s1;
    scanf("%d%d", &L, &K);
    cin>>s;
    for(int i = 0; i + K - 1 < L; i++){
        s1 = s.substr(i, K);// !!!从i开始的K个元素 不是i到K
        int num = stoi(s1);
        if(isPrime(num)){
            s1 = to_string(num);
            while(s1.size() < K)
                s1 = '0' + s1;
            cout<<s1;
            return 0;
        }
    }
    printf("404");
    return 0;
}

4,解题过程

第一搏

不断截取K个字符串,将其转化为int类型,并判断是否为质数(Prime);

#include<bits/stdc++.h>
using namespace std;
int L, K;
bool isPrime(int x){
    if(x <= 1) return false;
    for(int i = 2; i <= sqrt(x); i++){
        if(x % i == 0)
            return false;
    }
    return true;
}
int main(){
#ifdef ONLINE_JUDGE
#else
    freopen("1.txt", "r", stdin);
#endif // ONLINE_JUDGE
    string s, s1;
    scanf("%d%d", &L, &K);
    cin>>s;
    for(int i = 0; i + K - 1 < L; i++){
        s1 = s.substr(i, K);// !!!从i开始的K个元素 不是i到K
        int num = stoi(s1);
        if(isPrime(num)){
            printf("%d", num);
            return 0;
        }
    }
    printf("404");
    return 0;
}

第二搏

测试点2:注意到print in a line the first K-digit prime in consecutive digits of N,意思就是说如果质数为0023的话,要输出0023而不是23,于是

 

 

 

 

 

 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值