原题
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;
}