模拟即可。
class Solution {
public:
int getLucky(string s, int k) {
int n=0;
string t;
for(auto c:s) t+=to_string(c-'a'+1);
for(auto c:t) n+=c-'0';
while(k-->1){
int res=0;
while(n){
res+=n%10;
n/=10;
}
n=res;
}
return n;
}
};
时间复杂度:O(km),m为s的长度。
空间复杂度:O(m)。