[codewars][python][C++]Mumbling

8 篇文章 0 订阅
4 篇文章 0 订阅

This time no story, no theory. The examples below show you how to write function accum:

Examples:

accum("abcd") -> "A-Bb-Ccc-Dddd"
accum("RqaEzty") -> "R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy"
accum("cwAt") -> "C-Ww-Aaa-Tttt"

The parameter of accum is a string which includes only letters from a..z and A..Z.

思路:遍历拼接字符串,使用upper和lower函数

代码如下:

【python】

def accum(s):
    count=0
    ret=''
    for i in s:
        count+=1
        ret+=i.upper()
        for index in range(count-1):
            ret+=i.lower()
        if count<len(s):
            ret+='-'
    return ret

"Best One

def accum(s):
    return '-'.join(c.upper() + c.lower() * i for i, c in enumerate(s))

【C++】

class Accumul
{
public:
    static std::string accum(const std::string &s);
};

std::string Accumul::accum(const std::string &s)
{
    int length = s.size();
    int count = 0;
    std::string ret = "";
    for (int i = 0; i < length; i++)
    {
        char upc = s[i];
        char lowc = s[i];
        if (upc > 'Z')
        {
            upc += ('A'-'a');
        }
        else
        {
            lowc -= ('A'-'a');
        }
        count++;
        ret += upc;
        ret += std::string(count - 1, lowc);
        if (count < length)
        {
            ret += "-";
        }
    }
    return ret;
}

"Best One

class Accumul
{
public:
    static std::string accum(const std::string &s) {
      std::string result;
      for (int i = 0; i < s.length(); i++) {
        result.append("-");
        result.append(std::string(1,toupper(s[i])));
        result.append(std::string(i,tolower(s[i])));
      }
      return result.substr(1,result.length());
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值