Reverse or rotate? -- 6Kyu

原题

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.
If
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 "".

Examples:

revrot("123456987654", 6) --> "234561876549"
revrot("123456987653", 6) --> "234561356789"
revrot("66443875", 4) --> "44668753"
revrot("66443875", 8) --> "64438756"
revrot("664438769", 8) --> "67834466"
revrot("123456779", 8) --> "23456771"
revrot("", 8) --> ""
revrot("123456779", 0) --> "" 
revrot("563000655734469485", 4) --> "0365065073456944"

分析

本题主要是数字字符串处理。主要分为三个要点。

  1. 数组字符串累计求和
  2. 字符串反转
  3. 字符串旋转

这三个问题都可以使用STL算法函数模板解决。

参考答案

#include 
#include 
using namespace std;

class RevRot
{
public:
    static std::string revRot(const std::string &str, unsigned int sz){
      if(0 == sz or str.empty() or sz > str.size()){
        return "";
      }
      size_t count(str.size()/sz);
      string res(str,0,count*sz);// 保留满足sz部分

      auto it = res.begin();
      while(it < res.end()){
        if(accumulate(it,it+sz,'0',[](char r,char l){return (r-'0')+(l-'0');})%2){
          rotate(it,it+1,it+sz);
        }else{
          reverse(it,it+sz);
        }
        it += sz;
      }
      return res;
    };
};

说明

其它

你可能感兴趣的:(Reverse or rotate? -- 6Kyu)