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为例
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//來源:简书//著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
阅读全文
0 0
- Build Tower -- 6 kyu
- Consecutive strings -- 6 kyu
- codewar-6kyu-Vasya
- Reverse or rotate? -- 6 kyu
- Sicily 1919. Build the Tower
- codewars-6kyu-give a diamond(打印菱形)
- Tower
- tower
- Return location -- 8kyu
- Directions Reduction -- 5 kyu
- 1-6 Tower of Hanoi
- 算法学习【6】 - 1028. Hanoi Tower Sequence
- 【codewarns-8kyu】- Arguments to Binary addition
- Is this a triangle? -- 7kyu
- Parts of a list -- 7 kyu
- Moves in squared strings (I) -- 7Kyu
- Ivory Tower
- hdu2971 Tower
- 存储器类型
- 进程内存分配
- c# IComparer比较字符串
- 【洛谷2704】【NOI2001】炮兵阵地
- POJ1724 ROADS
- Build Tower -- 6 kyu
- Spring RestTemplate中几种常见的请求方式
- PHP如何实现判断请求是否来自手机和请求是否来自浏览器的问题
- SharedPreferences(偏好设定;轻量级的存储)
- 读书笔记∣概率论沉思录 01
- 编写注册新用户的模块JavaScript
- javaweb中的路径问题
- javaEE之远程方法调用(RMI)
- 优秀的数据分析师应该关注哪些网站