1663. 具有给定数值的最小字符串
为保证权益,题目请参考 1663. 具有给定数值的最小字符串(From LeetCode).
解决方案1
CPP
C++
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
class Solution {
public:
string getSmallestString(int n, int k) {
if (n > k) {
// it can't happened
return "";
}
int zNum = (k - n) / 25;
int bZ = (k - n) % 25;
string ans = "";
for (int i = 0; i < n; i++) {
if (i > n - zNum - 1) {
ans.push_back('z');
} else if (i == n - zNum - 1) {
ans.push_back(char(('a' - 1) + bZ + 1));
} else {
ans.push_back('a');
}
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31