classSolution { publicintgetLucky(String s, int k) { StringBuildersb=newStringBuilder(); for (inti=0; i < s.length(); ++i) { charch= s.charAt(i); sb.append(ch - 'a' + 1); } Stringdigits= sb.toString(); for (inti=1; i <= k && digits.length() > 1; ++i) { intsum=0; for (intj=0; j < digits.length(); ++j) { charch= digits.charAt(j); sum += ch - '0'; } digits = Integer.toString(sum); }
return Integer.parseInt(digits); } }
[sol1-C#]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
publicclassSolution { publicintGetLucky(string s, int k) { StringBuilder sb = new StringBuilder(); foreach (char ch in s) { sb.Append(ch - 'a' + 1); } string digits = sb.ToString(); for (int i = 1; i <= k && digits.Length > 1; ++i) { int sum = 0; foreach (char ch in digits) { sum += ch - '0'; } digits = sum.ToString(); }
returnint.Parse(digits); } }
[sol1-Python3]
1 2 3 4 5 6 7 8 9 10 11
classSolution: defgetLucky(self, s: str, k: int) -> int: digits = "".join(str(ord(ch) - ord("a") + 1) for ch in s)
for i inrange(k): iflen(digits) == 1: break total = sum(int(ch) for ch in digits) digits = str(total) returnint(digits)
[sol1-C]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
intgetLucky(char * s, int k) { int n = strlen(s); char digits[n * 2 + 1]; int pos = 0; for (int i = 0; i < n; i++) { pos += sprintf(digits + pos, "%d", s[i] - 'a' + 1); } int len = pos; for (int i = 1; i <= k && len > 1; ++i) { int sum = 0; for (int j = 0; j < len; j++) { sum += digits[j] - '0'; } len = sprintf(digits, "%d", sum); } return atoi(digits); }
[sol1-Golang]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
funcgetLucky(s string, k int)int { t := []byte{} for _, c := range s { t = append(t, strconv.Itoa(int(c-'a'+1))...) } digits := string(t) for i := 1; i <= k && len(digits) > 1; i++ { sum := 0 for _, c := range digits { sum += int(c - '0') } digits = strconv.Itoa(sum) } ans, _ := strconv.Atoi(digits) return ans }
[sol1-JavaScript]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
var getLucky = function(s, k) { let sb = ''; for (let i = 0; i < s.length; ++i) { const ch = s[i]; sb += '' + ch.charCodeAt() - 'a'.charCodeAt() + 1; } let digits = sb.toString(); for (let i = 1; i <= k && digits.length > 1; ++i) { let sum = 0; for (let j = 0; j < digits.length; ++j) { const ch = digits[j]; sum += ch.charCodeAt()- '0'.charCodeAt(); } digits = '' + sum; }
return0 + digits; };
复杂度分析
时间复杂度:O(n),其中 n 是字符串 s 的长度。构造第一次操作前的字符串需要 O(n) 的时间。由于 n \leq 100,在最坏情况下: