[Kata 7 C++]Alphabetical Grid

描述

You need to write a function grid that returns an alphabetical grid of size NxN, where a = 0, b = 1, c = 2…
Examples:

grid(4)

a b c d
b c d e
c d e f
d e f g

grid(10)

a b c d e f g h i j
b c d e f g h i j k
c d e f g h i j k l
d e f g h i j k l m
e f g h i j k l m n
f g h i j k l m n o
g h i j k l m n o p
h i j k l m n o p q
i j k l m n o p q r
j k l m n o p q r s

After “z” comes “a”
If function receive N < 0 should return:“”

解决方案

1

#include <string>

std::string grid(int n) {
  std::string s = "abcdefghijklmnopqrstuvwxyz";
  std::string ans;
  if(n < 0)
    return "";
  for(int i = 0; i < n; i++){
    for(int j = 0; j < n; j++){
      ans += s[(i + j) % 26];
      ans += j == n - 1 ? "" : " ";
    }
    ans += i == n - 1 ? "" : "\n";
  }
  return ans;
}

使用append(char)的方式会不通过。 可能取地址后出现问题,有人测试过+= 比append 高效,在C#中+=会产生GC 也许C++机制不同

2

#include <string>
std::string grid(int n){
    if(n==0)return "";

    char c='a';
    int no=0,ano=0;
    std::string sum;
    for(int i=0;i<n;i++){
        for(int j=0;j<n;j++){
            sum+=c+no;
            if(j!=n-1)sum+=' ';
            if(no+1!=26)no++;
            else no=0;
        }
        if(ano+1!=26)ano++;
        else ano=0;
        no=ano;
        if(i!=n-1)sum+="\n";
    }
    return sum;
}

+= char 也好使

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值