PAT A 1031 Hello World for U

Given any string of N (>=5) characters, you are asked to form thecharacters into the shape of U. For example, "helloworld" can be printedas:

h  d
e  l
l  r
lowo

That is, the characters must be printed in the original order, startingtop-down from the left vertical line with n~1~ characters, then left toright along the bottom line with n~2~ characters, and finally bottom-upalong the vertical line with n~3~ characters. And more, we would like Uto be as squared as possible -- that is, it must be satisfied that n~1~= n~3~ = max { k| k <= n~2~ for all 3 <= n~2~ <= N } with n~1~

  • n~2~ + n~3~ - 2 = N.

Input Specification:

Each input file contains one test case. Each case contains one stringwith no less than 5 and no more than 80 characters in a line. The stringcontains no white space.

Output Specification:

For each test case, print the input string in the shape of U asspecified in the description.

Sample Input:

helloworld!

Sample Output:

h   !
e   d
l   l
lowor

pta默认gets不安全,不能用,只能用scanf。。。。

方法一,输入到数组中,然后再输出

#include<stdio.h>
#include<string.h>
int main() {
	char str[85];
	char a[100][100];
	scanf("%s",str);
	int n = strlen(str);
	int n1 = (n + 2) / 3, n3 = n1, n2 = n + 2 - 2 * n1;
	int k = 0;
	for (int i = 1; i <= n1; i++)        //别忘了初始化为空格,没赋值的输出会出错
		for (int j = 1; j <= n2; j++)
			a[i][j] = ' ';
	for (int i = 1; i <= n1; i++) {        //第一列
		a[i][1] = str[k++];
	}
	for (int i = 2; i <= n2; i++) {        //最后一行
		a[n1][i] = str[k++];
	}
	for (int i = n1-1; i >= 1; i--) {        //最后一列
		a[i][n2] = str[k++];
	}
	for (int i = 1; i <= n1; i++) {        //输出
		for (int j = 1; j <= n2; j++) {
			printf("%c", a[i][j]);
		}
		printf("\n");        //输出完一行要记得换行啊。。不然图形不对。。
	}
	return 0;
}
方法二,直接输出
#include<stdio.h>
#include<string.h>
int main() {
	char str[85];
	scanf("%s",str);
	int n = strlen(str);
	int n1 = (n + 2) / 3, n3 = n1, n2 = n + 2 - 2 * n1;
	int k = 0;
	for (int i = 0; i <= n1-2; i++) {
		printf("%s", str[i]);
		for (int j = 1; j <= n2 - 2; j++) {
			printf(" ");
		}
		printf("%c\n", str[n - 1 - i]);
	}
	for (int i = 0; i < n2; i++) {
		printf("%c", str[n1 - 1 + i]);
	}
	printf("\n");
	return 0;
}


猜你喜欢

转载自blog.csdn.net/joah_ge/article/details/80560394
今日推荐