洛谷 P1603 斯诺登的密码 题解 (字符串C/C++)

题目链接点我

思路如下:

  1. 数字 1 ~ 20 存到字符串数组中(对应数组下标加1即为该英文所代表的的数字),非正规的几个字母一会特殊判断;
  2. 将输入都转为小写;
  3. 将数字平方取模后存入整型数组,然后排序;
  4. 最后按序输出数组中的数字即可。(这里有几个输出细节要特殊处理,比如找到第一个非0的数,如果是个位数不需要输出前导0,后续的个位数的话要补一个0,详见代码)

//P1603 斯诺登的密码
//#define LOCAL
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <cmath>
#include <algorithm>
#include <cctype>
#include <sstream>
#define inf 0x3f3f3f3f
#define eps 1e-6
using namespace std;
#define clr(x) memset(x,0,sizeof((x)))
const int maxn = 1e4+1;//2e6+1
#define MAX(a,b,c) ((a)>(b)?((a)>(c)?(a):(c)):((b)>(c)?(b):(c)))
#define _max(a,b) ((a) > (b) ? (a) : (b))
#define _min(a,b) ((a) < (b) ? (a) : (b))
#define _for(a,b,c) for(int a = b;a<c;a++)
string s;

string str[] = {
    
    "one", "two", "three", "four","five", "six", "seven", "eight", 
				"nine", "ten", "eleven", "twelve", "thirteen", "fourteen", 
				"fifteen", "sixteen", "seventeen", "eighteen", "nineteen", 
				"twenty"};

void toLow() {
    
    
	int len = s.length();
	for(int i = 0;i<len;i++) {
    
    
		s[i] = tolower(s[i]);
	}
}

int main()
{
    
    
#ifdef LOCAL 
	freopen("data.in","r",stdin);
	freopen("data.out","w",stdout);
#endif
	int i,num,j=0;
	int buf[100];
	clr(buf);
	while(cin>>s&&s!=".") {
    
    
		num = 0;
		toLow();
		//取数
		if(s=="a"||s=="another"||s=="first") {
    
    
			num = 1;
		}
		else if(s=="both"||s=="second") {
    
    
			num = 2;
		}
		else if(s=="third") {
    
    
			num = 3;
		}
		else {
    
    
			for(i = 0;i<20;i++) {
    
    
				if(str[i]==s)break;
			}	
			if(i<20)num = i+1;
		}
		//处理
		if(num) {
    
    
			num = pow(num,2);
			num%=100;
			buf[j++] = num;
		}
	}
	
	int tag = 1;
	if(!j||buf[j-1]==0)cout<<0;//没有符合要求的数字出现,或者每个数字平方取模都是0,则输出0
	else {
    
    
		sort(buf,buf+j);
		for(int k = 0;k<j;k++) {
    
    
			if(buf[k]==0)continue;
			if(tag&&buf[k]>0&&buf[k]<10) {
    
    
				cout<<buf[k];
				tag = 0;
			}
			else printf("%02d",buf[k]);
		}
	}
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Jason__Jie/article/details/112795943