Open carloscn opened 1 year ago
fn sum_number(v:i32) -> i32
{
let mut k:i32 = v;
let mut ret:i32 = 0;
while k != 0 {
ret += k % 10;
k /= 10;
}
return ret;
}
pub fn get_lucky(s: &str, k: i32) -> i32
{
if s.len() < 1 {
return 0;
}
let mut ret:i32 = 0;
let s_v:Vec<char> = s.chars().collect();
let mut z:i32 = 1;
for i in 0..s_v.len() {
let a = (s_v[s_v.len() - 1 - i] as u8 - 'a' as u8 + 1) as i32;
ret += a * z;
z *= 10;
}
for i in 0..k {
ret = sum_number(ret);
}
return ret;
}
Description
You are given a string s consisting of lowercase English letters, and an integer k.
First, convert s into an integer by replacing each letter with its position in the alphabet (i.e., replace 'a' with 1, 'b' with 2, ..., 'z' with 26). Then, transform the integer by replacing it with the sum of its digits. Repeat the transform operation k times in total.
For example, if s = "zbax" and k = 2, then the resulting integer would be 8 by the following operations:
Convert: "zbax" ➝ "(26)(2)(1)(24)" ➝ "262124" ➝ 262124 Transform @1: 262124 ➝ 2 + 6 + 2 + 1 + 2 + 4 ➝ 17 Transform @2: 17 ➝ 1 + 7 ➝ 8 Return the resulting integer after performing the operations described above.
Example 1:
Input: s = "iiii", k = 1 Output: 36 Explanation: The operations are as follows:
Example 2:
Input: s = "leetcode", k = 2 Output: 6 Explanation: The operations are as follows:
Input: s = "zbax", k = 2 Output: 8
Constraints:
1 <= s.length <= 100 1 <= k <= 10 s consists of lowercase English letters.