PAT甲级 1031 Hello World for U
题目说明:
给你一个字符串,将其输出为U型,为保证看起四方一点,规定左边长n1、底边长n2、右边长n3,因为有两个重叠的部分,所以 总长度N = sum(ni) - 2,且n1 = n3 要在 <= n2的情况下尽可能大,可见求出任意一个ni就行
输入输出:
Sample Input:
helloworld!
Sample Output:
h !
e d
l l
lowor
code:
#include<string>
#include<iostream>
using namespace std;
int main()
{
string s;
cin>>s;
int len = s.size();
int n2 = 3;
for(; n2 < len; n2++) //the minimum value of n2 is 3 (for N = 5),this function is to find the max n1 = n3 <= n2
{
if(((len + 2) - n2) % 2 == 0 )
{
if((((len + 2) - n2) / 2) <= n2)
break;
}
}
int k = n2 - 2; //the number of blank
for(int i = 0; i <= (len - n2) / 2; i++)
{
cout<<(s[i]);
if(i == (len - n2) / 2)
{
for(int j = i + 1; j < i + k + 1; j++)
cout<<(s[j]);
}
else
for(int j = 0; j < k; j++)
cout<<(' ');
cout<<(s[len - i - 1])<<endl;
}
return 0;
}
结果:


浙公网安备 33010602011771号