Loading... # Problem A - [字符串转化后的各位数字之和](https://leetcode-cn.com/problems/sum-of-digits-of-string-after-convert/) ## 方法一:模拟 > 按照题意模拟即可 ### 比赛中代码: <div class="panel panel-default collapse-panel box-shadow-wrap-lg"><div class="panel-heading panel-collapse" data-toggle="collapse" data-target="#collapse-9c9d5bfcf864aa8aa51033d3a9c420e527" aria-expanded="true"><div class="accordion-toggle"><span style="">**C++**</span> <i class="pull-right fontello icon-fw fontello-angle-right"></i> </div> </div> <div class="panel-body collapse-panel-body"> <div id="collapse-9c9d5bfcf864aa8aa51033d3a9c420e527" class="collapse collapse-content"><p></p> ```cpp class Solution { public: int getLucky(string s, int k) { int a[26]; for (int i = 0; i < 26; ++ i) a[i] = i + 1; string t = ""; for (auto c : s) { int id = c - 'a'; t += to_string(a[id]); } while (k -- ) { //cout << t << endl; int tm = 0; for (auto c : t) { tm += c - '0'; } t = to_string(tm); } int ans = 0; for (auto c : t) { ans = ans * 10 + c - '0'; } return ans; } }; ``` ~~ps:STL还是用的不够熟练,还有很大进步空间~~ <p></p></div></div></div> ### 赛后优化代码: <div class="tab-container post_tab box-shadow-wrap-lg"> <ul class="nav no-padder b-b scroll-hide" role="tablist"> <li class='nav-item active' role="presentation"><a class='nav-link active' style="" data-toggle="tab" aria-controls='tabs-1ae38be11229eccdfb62fbf094a2febd870' role="tab" data-target='#tabs-1ae38be11229eccdfb62fbf094a2febd870'>**C++**</a></li><li class='nav-item ' role="presentation"><a class='nav-link ' style="" data-toggle="tab" aria-controls='tabs-607857dd93df2858066eb8b6ca093af8611' role="tab" data-target='#tabs-607857dd93df2858066eb8b6ca093af8611'>**Python 3**</a></li> </ul> <div class="tab-content no-border"> <div role="tabpanel" id='tabs-1ae38be11229eccdfb62fbf094a2febd870' class="tab-pane fade active in"> ```cpp class Solution { public: int getLucky(string s, int k) { string ans; for (char c : s) ans += to_string(c - 96); while (k -- ) { int sum = 0; for (char c : ans) sum += c - '0'; ans = to_string(sum); } return stoi(ans); } }; ``` </div><div role="tabpanel" id='tabs-607857dd93df2858066eb8b6ca093af8611' class="tab-pane fade "> ```python class Solution: def getLucky(self, s: str, k: int) -> int: snum = ''.join(map(lambda x : str(ord(x) - 96), s)) for _ in range(k): snum = str(sum(map(int, snum))) return int(snum) ``` ~~ps:除了Python牛皮咱还能说啥?~~ </div> </div> </div> ### 复杂度分析: * 时间复杂度:$O(k|S|)$ * 空间复杂度:$O(|S|)$ Last modification:August 18, 2021 © Allow specification reprint Support Appreciate the author AliPayWeChat Like 看着给点?(●'◡'●)?