2020年3月20日 星期五

2.3-Square Code

解題心得:
輸入資料後,首先要找出方塊的長跟寬。我想像中一開始就單純一行,然後有個可移動的直線控制一行的數量,一次往內縮減一格,直到符合條件才停止。
其中
width = len / height + (len % height ? 1 : 0);
這行是看看長度除以高度能否被整除?如果不能,代表說有不成行的,要加一。
最後就是輸出答案。
程式碼:
#include <iostream>
#include <string>
using namespace std;

int main()
{
 int len, width, height; //height >= width
 string s;
 while (cin >> s)
 {
  len = s.size();
  height = 1;
  width = len / height;
  while (width > height) // find height & width
  {
   height++;
   width = len / height + (len % height ? 1 : 0); //make sure width is right
  }
  for (int i = 0; i < height; i++) // print squre
  {
   for (int j = 0; j < width; j++)
   {
    if (i + j * height < len)
     cout << s[i + j * height];
    else
     cout << " ";
   }

   cout << endl;
  }
 }
 return 0;
}


另一個解法
#include <iostream>
#include <string>
using namespace std;

int main() {
 string text;
 while (cin >> text)
 {
  int n = 1;
  while (n*n < text.size())
   n++;
  if (n*n == text.size())
  {
   for (int i = 0; i < n; i++)
   {
    for (int j = 0; j < n; j++)
     cout << text[i + n * j];
    cout << endl;
   }
  }
  else
  {
   int w = text.size() % n == 0 ? text.size() / n : text.size() / n + 1;
   for (int i = 0; i < n; i++)
   {
    for (int j = 0; j < w; j++)
    {
     if (i + n * j >= text.size())
      cout << " ";
     else
      cout << text[i + n * j];
    }

    cout << endl;
   }
  }
 }
    return 0;
}

沒有留言:

張貼留言