序号互换
时间限制:
1000 ms | 内存限制:
65535 KB
难度:
2
-
描述
-
Dr.Kong设计了一个聪明的机器人卡多,卡多会对电子表格中的单元格坐标快速计算出来。单元格的行坐标是由数字编号的数字序号,而列坐标使用字母序号。观察字母序号,发现第1列到第26列的字母序号分别为A,B,…,Z,接着,第27列序号为AA,第28列为AB,依此类推。
若给Dr.Kong的机器人卡多一个数字序号(比如32),它能很快算出等价的字母序号(即AF),若给机器人一个字母序号(比如AA)),它也能很快算出等价的数字序号(27),你能不能与卡多比试比试,看谁能算得更快更准确。
-
输入
-
第一行: N 表示有多少组测试数据。
接下来有N行, 每行或者是一个正整数,或者是一个仅由大写字母组成的字符串。
输入保证,所有数字序号和字母序号对应的数字序号均 ≤ 2*10^9
输出
- 对于每一行测试数据,输出一行。如果输入为一个正整数序号,则输出等价的字母序号;如果输入为字符串,则输出等价的数字序号。 样例输入
-
3 27 G AA
样例输出
-
AA 7 27
-
第一行: N 表示有多少组测试数据。
题解:OJ的后台数据是AA和Z是一样的,都是26。那就和题意不一样了。按后台数据,附上代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
int charToNum(char* str)
{
int num = 0;
int len = strlen(str);
int i = 0;
while(i < len)
{
num += (str[i] - 'A' + 1) * pow(26, (len - i - 1));
i++;
}
return num;
}
void numToChar(int num, char* str)
{
int i = 0;
while(num > 0)
{
char c = 'A' + num % 26 - 1;
int a = num /= 26;
if(c == 'A'-1)
{
str[i] = 'Z';
num = a-1;
}
else
{
str[i] = c;
num = a;
}
i++;
}
str[i] = '\0';
num = i-1;
i = 0;
while(num > i)
{
char temp = str[num];
str[num] = str[i];
str[i] = temp;
num--;
i++;
}
}
int main()
{
int num = 0;
scanf("%d", &num);
while(num--)
{
char test[10];
scanf("%s", test);
if(test[0] <= '9' && test[0] > '0')
{
int testNum = atoi(test);
char testStr[10];
numToChar(testNum, testStr);
printf("%s\n", testStr);
}
else
printf("%d\n", charToNum(test));
}
return 0;
}
按题意附上代码:(注意这个代码是不能AC的,只是我按题意写的)
#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<string.h>
#include<string>
using namespace std;
void fun1(char ch[])
{
int x = 0, len = strlen(ch);
for(int i = 0; i < len; i++)
{
x *= 10;
x += ch[i]-'0';
}
while(x)
{
int temp;
temp = x%26;
x /= 27;
if(temp == 0) printf("Z");
else printf("%c", 'A'+temp-1);
}
printf("\n");
}
void fun2(char ch[])
{
int x = 0, len = strlen(ch);
for(int i = 0; i < len; i++)
{
x *= 26;
x += ch[i]-'A'+1;
}
printf("%d\n", x);
}
int main()
{
int T;
scanf("%d", &T);
while(T--)
{
char ch[20];
scanf("%s", ch);
if(ch[0]>'0' && ch[0]<'9')
fun1(ch);
else
fun2(ch);
}
}