NYOJ303(字符串)
题意:其实就是字母序号与数字序号的转换,有点类似字典序。
解题思路:不论输入的是字符串还是数字都用一个字符数组来存储,只需要判断字符串的第一个字符是数字还是字母,然后分情况解决。众所周知,英文字母有26个,这就是重点所在。
注意:当字符串很长时,所求的数字序号会超过整型范围,所以定义为long long型,或 __int 64.(但NYOJ不识别__int 64)。
View Code
1 #include<iostream>
2 #include<cstdio>
3 #include<cstring>
4 #include<stack>//栈操作
5 using namespace std;
6 #define MAX 10005
7 char str[MAX];
8 char ch[]="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
9 int main()
10 {
11 int i,j,n,k,a,len;
12 stack<int> st;
13 cin>>n;
14 while(n--)
15 {
16 cin>>str;
17 if(!isalpha(str[0]))//判断第一个字符是字母还是数字
18 {
19 sscanf(str,"%d",&a);//把字符串转换为数字
20 while(a>0)
21 {
22 k=a%26;
23 a/=26;
24 if(k==0) { k=26; a--;}
25 st.push(k);//进栈
26 }
27 while(!st.empty())
28 {
29 cout<<ch[st.top()-1];//输出栈顶元素
30 st.pop();//出栈
31 }
32 cout<<endl;
33 }
34 else
35 {
36 long long sum=0;
37 len=strlen(str);
38 for(i=0;i<len;i++)
39 {
40 int x=1;
41 for(j=len-1-i;j>0;j--)
42 x*=26;
43 sum+=(str[i]-'A'+1)*x;
44 }
45 cout<<sum<<endl;
46 }
47 }
48 return 0;
49 }
2 #include<cstdio>
3 #include<cstring>
4 #include<stack>//栈操作
5 using namespace std;
6 #define MAX 10005
7 char str[MAX];
8 char ch[]="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
9 int main()
10 {
11 int i,j,n,k,a,len;
12 stack<int> st;
13 cin>>n;
14 while(n--)
15 {
16 cin>>str;
17 if(!isalpha(str[0]))//判断第一个字符是字母还是数字
18 {
19 sscanf(str,"%d",&a);//把字符串转换为数字
20 while(a>0)
21 {
22 k=a%26;
23 a/=26;
24 if(k==0) { k=26; a--;}
25 st.push(k);//进栈
26 }
27 while(!st.empty())
28 {
29 cout<<ch[st.top()-1];//输出栈顶元素
30 st.pop();//出栈
31 }
32 cout<<endl;
33 }
34 else
35 {
36 long long sum=0;
37 len=strlen(str);
38 for(i=0;i<len;i++)
39 {
40 int x=1;
41 for(j=len-1-i;j>0;j--)
42 x*=26;
43 sum+=(str[i]-'A'+1)*x;
44 }
45 cout<<sum<<endl;
46 }
47 }
48 return 0;
49 }