Build Tower -- 6 kyu

原题

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为例

行数前空格数*数后空格数
0515
1434
2353
3272
4191
50111

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
//來源:简书
//著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值