A题

5980. 将字符串拆分为若干长度为 k 的组

C++

  1. class Solution {
  2. public:
  3. vector<string> divideString(string s, int k, char fill) {
  4. vector<string> strarray;
  5. string str = "";
  6. int j = 0;
  7. for (auto i = 0; i < s.size(); ++ i) {
  8. str = str + s[i];
  9. ++ j;
  10. if (j == k) {
  11. strarray.push_back(str);
  12. str = "";
  13. j = 0;
  14. }
  15. }
  16. if (str.size() > 0 && str.size() < k) {
  17. char schar[2] = {fill, 0};
  18. string sfill = schar;
  19. for (auto i = str.size(); i < k; ++ i) str = str + sfill;
  20. strarray.push_back(str);
  21. return strarray;
  22. }
  23. };

B题

C++

5194. 得到目标值的最少行动次数

  1. class Solution {
  2. public:
  3. int minMoves(int target, int maxDoubles) {
  4. int addcount = 0, redoublecount = 0;
  5. while (target >= 2) {
  6. if (redoublecount < maxDoubles) {
  7. int modnum = target % 2;
  8. addcount += modnum;
  9. ++ redoublecount;
  10. target = target / 2;
  11. }
  12. else {
  13. addcount += (target - 1);
  14. break;
  15. }
  16. }
  17. return addcount + redoublecount;
  18. }
  19. };