NYOJ-303-序号互换(第四届河南省程序设计大赛A题(模拟))

序号互换

时间限制: 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

题解: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);
    }
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值