年号字串-2019届蓝桥杯B组(脑筋急转弯)
https://www.lanqiao.cn/problems/605/learning/?contest_id=51
题解
这题看似是一道进制转换题目
实则还有很多坑点
比如对于数字702
我们通常进制转换会将其变为110
然而702对应的实际字母是ZZ
问题出在哪了?
实际上这道题转换后不能存在0
我们得到转换后的110这种串需要先预处理一下
把所有的0向前借位,然后就是ZZ了
for(int i=0;i<s-1;i++)
{
if(t[i]<=0)
{
t[i+1]--;
t[i]+=26;
}
}
注意是t[i]+=26而不是t[i]=26
因为t[i]可能因为借位变成负数
然后这道题就轻松解决了
#include<stdio.h>
#include<iostream>
#include<cstdlib>
#include<string.h>
#include<algorithm>
using namespace std;
int main()
{
//freopen("uva.txt","r",stdin);
int n;
scanf("%d",&n);
string t;
int s=0;
while(n)
{
t+=n%26;
n/=26;
s++;
}
string ans;
for(int i=0;i<s-1;i++)
{
if(t[i]<=0)
{
t[i+1]--;
t[i]+=26;
}
}
if(t[s-1]==0) s--;
for(int i=s-1;i>=0;i--)
{
ans+=t[i]+'A'-1;
}
cout<<ans;
return 0;
}