Build Tower -- 6 kyu

来源:互联网 发布:淘宝服务市场退款 编辑:程序博客网 时间:2024/06/07 22:55

原题

https://www.codewars.com/kata/576757b1df89ecf5bd00073b/train/cpp

题目

Build Tower

Build Tower by the following given argument:
number of floors (integer and always greater than 0).

Tower block is represented as *

  • Python: return a list;
  • JavaScript: returns an Array;
  • C#: returns a string[];
  • PHP: returns an array;
  • C++: returns a vector;
  • Haskell: returns a [String];

Have fun!
Example:
a tower of 3 floors looks like below

[  '  *  '  ' *** '  '*****']

a tower of 6 floors looks like below

[  '     *     '  '    ***    '   '   *****   '   '  *******  '   ' ********* '   '***********']

分析

以6行tower为例

行数 前空格数 *数 后空格数 0 5 1 5 1 4 3 4 2 3 5 3 3 2 7 2 4 1 9 1 5 0 11 1

n行tower,第i行前空格数和后空格数都为n-i-1个,‘ * ‘数为(2*i+1)个

代码

class Kata{public:    std::vector<std::string> towerBuilder(int nFloors)    {        std::vector<std::string> str;        for(size_t i = 0; i < nFloors;i++)        {              std::string spaces1((nFloors-i-1),' ');              std::string stars((2*(i+1)-1),'*');              str.push_back(spaces1+stars+spaces1);        }        return str;    }};

参考代码

#include <iostream>#include <string> #include <vector> using namespace std; class Kata{ public:  vector<string> towerBuilder(int nFloors){  size_t len = 2*nFloors-1;  for(size_t i=0;i<nFloors;i++){      fill_n(res[i].begin()+(nFloors-i-1),2*i+1,'*'); } return res;  } };//容器初始化时可以指定初始化值,这样可以避免另外的复制操作。//作者:jdzhangxin//链接:http://www.jianshu.com/p/9bed458fa1db//來源:简书//著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
原创粉丝点击