题目要求:在横宽的前提下接近正方形
缺了一条边,不能用面积来判别“接近方形”,要算width和height的差值
函数单调,故用pre记录上一次的结果,循环比较即可
#include<stdio.h> #include<math.h> int getHeight(int length){ int preDelta = length; int preHeight = 0; int i = length;//字符串最短为5 for(;i>=3;i--){//题目要求是在“横宽”的前提下接近方形 if((length-i)%2!=0) continue;//无法分配,跳过 int height = (length-i)/2+1; if(height>i) break;//不是横宽而是纵长,跳出循环 int delta = abs(height-i); //printf("width=%d,height=%d,%d\n",i,height,delta); if(delta>preDelta) return preHeight; preDelta = delta; preHeight = height; } return preHeight; } char* getSpace(int len){ char* space = (char*)malloc(sizeof(len)); int i=0; for(;i<len;i++){ space[i]=' '; } space[i] = '\0'; return space; } void Question2_5(){//习题2.5 浙江大学 HelloWorldForU char str[80]; while(scanf("%s",str)!=EOF){ int count = 0; for(;str[count]!='\0';count++){} int height = getHeight(count); int width = count-2*height+2; //printf("%d\n",height); char* space = getSpace(width-2); int i=0; for(;i<height-1;i++){ printf("%c",str[i]); printf("%s",space); printf("%c\n",str[count-i-1]); } int j=height-1; for(;j<count-height+1;j++){ printf("%c",str[j]); } printf("\n"); } } int main(){ Question2_5(); return 0; }