Reverse or rotate? -- 6 kyu
来源:互联网 发布:剑灵最新优化设置 编辑:程序博客网 时间:2024/05/22 21:54
原题
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
- Reverse or rotate? -- 6 kyu
- Build Tower -- 6 kyu
- Consecutive strings -- 6 kyu
- codewar-6kyu-Vasya
- reverse,reverse_copy,rotate,rotate_copy
- [leetcode] Rotate and Reverse
- cycle,reverse,rotate linked list
- codewars-6kyu-give a diamond(打印菱形)
- STL 之reverse,reverse_copy,rotate,rotate_copy
- STL 之reverse,reverse_copy,rotate,rotate_copy
- Return location -- 8kyu
- Directions Reduction -- 5 kyu
- Number of 1 Bits && Rotate Array && Reverse Bits
- leetcode之Number of 1 Bits,Reverse Bits,Rotate Array
- 一维数组Reverse翻转与rotate旋转
- Rotate object with mouse click or touch in Unity3D
- 2.2.6 Rotate List
- 6 rotate-image
- C#怎样在DataTable中使用linq查询
- 记录一次失败的流水灯实验
- 机器学习课堂笔记4
- c++11新特性总结
- KVM内存虚拟化 & EPT
- Reverse or rotate? -- 6 kyu
- 设计模式_创建形模式优缺点比较(8)
- 找出2个链表的第一个公共结点。
- 【暑假 8.23】Loi58 && 58plus夏令营检测试
- jsp中EL和jstl的区别
- 【模板】普通平衡树(洛谷3369/大视野3224)splay_tree
- System.Web.Helpers所在位置
- PS 图片简单处理(1寸照等)
- Xcode快捷操作