思路:
⭐进行无限次操作,但是 k 的取值小于 500 ,所以当 word 的长度大于 500 时就可以停止操作进行取值了
如果字符为 'z' ,单独处理使其变为 'a'
得到得到操作后的新字符串,和原字符串拼接
cpp
class Solution {
public:
string word = "a";
char kthCharacter(int k) {
while(word.size()<500){
string new_word = word;
for(int i=0; i<word.size(); i++){
new_word[i] = new_word[i] + 1;
if(new_word[i] == 'z' + 1) new_word[i] = 'a';
}
word = word + new_word;
}
return word[k-1];
}
};
注:
(1)字符串 string str = "a"
是双引号,单个字符是单引号
(2)数组下标从零开始
(3)判等是==
思路:
cpp
class Solution {
public:
int minElement(vector<int>& nums) {
int n = nums.size();
int min = 1e4;
for(int i=0; i<n; i++){
int a = nums[i];
//nums[i] = a%10 + a/10%10 + a/100%10+ a/1000%10 + a/10000%10;
int sum = 0;
while(nums[i] != 0){
sum = sum + nums[i] % 10;
//cout << sum << '\n';
nums[i] = nums[i] / 10;
}
if(sum < min) min = sum;
}
return min;
}
};
注:
(1)1e4
= 10的4次方 = 10000
(2)求数组的长度:nums.size()
(3)通用求一个数各个位的和:
cpp
int sum = 0;
while(nums[i] != 0){
sum = sum + nums[i] % 10;
cout << sum << '\n';
nums[i] = nums[i] / 10;
}
cpp
class Solution {
public:
long long maximumTotalSum(vector<int>& maximumHeight) {
int n = maximumHeight.size();
sort(maximumHeight.begin(), maximumHeight.end()); //默认从小到大
long long max_sum = 0;
while(n){
n--;
if(n>=1){
max_sum = max_sum + maximumHeight[n];
if(maximumHeight[n-1] >= maximumHeight[n]) maximumHeight[n-1] = maximumHeight[n] - 1;
if(maximumHeight[n-1] == 0) return -1;
}
else{
max_sum = max_sum + maximumHeight[n];
}
}
return max_sum;
}
};
注:
(1)排序 sort(maximumHeight.begin(), maximumHeight.end());
(2)求最后总和的时候可能会超过 int 的范围,用long long
(3)while 中的 n ,要注意和下面 n-1 的大小,分情况讨论