Reverse or rotate? -- 6 kyu

原题

https://www.codewars.com/kata/reverse-or-rotate/train/cpp

题目

The input is a string str of digits. Cut the string into chunks (a chunk here is a substring of the initial string) of size sz (ignore the last chunk if its size is less than sz).

If a chunk represents an integer such as the sum of the cubes of its digits is divisible by 2, reverse that chunk; otherwise rotate it to the left by one position. Put together these modified chunks and return the result as a string.

  • sz is <= 0 or if str is empty return “”
  • sz is greater (>) than the length of str it is impossible to take a chunk of size sz hence return “”

example:
revrot(“563000655734469485”, 4) –> “0365065073456944”

分析

此题是指输入一个数字字符串和块的长度sz,然后以sz将串划分成多个块,进行遍历

  • 如果块每一个数字之和为偶数,则反转该块;
  • 否则将以该块第二个为中心点,旋转
  • 如果串长小于块长或者块长<=0,都返回一个空string。
  • 最后一个块的长度如果不足sz,则忽略
代码
#include <string>

class RevRot
{
public:
    static std::string revRot(const std::string &strng, unsigned int sz);
};
std::string RevRot::revRot(const std::string &strng, unsigned int sz){
  size_t len = strng.size();
  if(sz == 0 || sz == 0||sz > len){
      return std::string();
  }
  unsigned chunk_num = len/sz;
  auto chunk_begin = begin(strng);
  auto chunk_end = chunk_begin+sz;
  size_t str_len = chunk_num*sz;
  std::string str;
  str.resize(str_len);
  auto str_begin = begin(str);
  for(size_t i = 0;i < chunk_num;i++){
   unsigned int sum = 0;
   for(size_t j = i*sz;j < (i+1)*sz;j++){
     sum += (int)(strng[j]-'0');
   }
   if(sum%2 == 0){
      reverse_copy(chunk_begin,chunk_end,str_begin);
   } else{
      rotate_copy(chunk_begin,chunk_begin+1,chunk_end,str_begin);
   }
   chunk_begin+=sz;
   chunk_end+=sz;
   str_begin+=sz;
  }
  return str;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值