PAT Grade A-Graphic Printing Type-1031 Hello World for U Problem Solving Ideas

1031 Hello World for U (20 分)

Insert picture description here

Ideas

To obtain the n1 and n2 that meet the requirements, this kind of question needs to enter several strings of different lengths to check. It
is difficult to modify the string string, and you need to use the string class function, so
there is another detail to use the char character array , after the char character array PAT The default setting is'\0', you have to seal it yourself

Code

#include <bits/stdc++.h>
using namespace std;

int main()
{
    
    
    string str;
    cin >> str;
    int len = str.length();
    
    int n1 ,n2;

    for (int i = 3;i<=len;i++) //获得满足要求的n1,n2
    {
    
    
        n2 = i;
        n1 = (len + 2 -n2)/2;
        if(n1<=n2)
        {
    
    
            n2 = len+ 2 - n1*2;
            break;
        }
    }
    
    char out[100] ;
    for(int i=0;i<n1;i++)
    {
    
    
        if(i!=n1-1)
        {
    
    
            out[0]=str[i];
            for(int j =1 ;j< n2-1 ;j++)
            {
    
    
                out[j] = ' ';
            }
            out[n2-1]=str[len-1-i];
            out[n2]='\0';    //PAT后置不默认为'\0',要自己封
            cout<<out<<endl;
        }
        else 
        {
    
    
            for(int j =n1-1 ;j< n1+n2-1 ;j++)
            {
    
    
                out[j-n1+1] = str[j];
            }
            out[n2]='\0';
            cout<<out;
        }
        
    }
    
}

Guess you like

Origin blog.csdn.net/weixin_43999137/article/details/114036893