Re: [閒聊] 每日leetcode

看板Marginalman作者 (caster )時間1年前 (2024/09/03 08:38), 編輯推噓1(100)
留言1則, 1人參與, 1年前最新討論串797/1548 (看更多)
※ 引述《enmeitiryous (enmeitiryous)》之銘言: : 今天是easy : 題目: : 1945 sum of digits of string after convert : 給你一個英文字串將他依照a=1,b=2...的方式轉換成一串數字後,求這串數字在經過 : k次把每一位數總和後的整數為何? : 思路: : 照做,使用to_string和-'0'來進行字串和整數的互換 : int getLucky(string s, int k) { : string pre_ans=""; : for(int i=0;i<s.size();++i){ : pre_ans+=to_string(s[i]-96); : } : int ans=0; : while(k!=0){ : ans=0; : k--; : for(int j=0;j<pre_ans.size();++j){ : ans+=(pre_ans[j]-'0'); : } : pre_ans=to_string(ans); : } : return ans; : } 思路: 照著敘述做 Python Code: class Solution: def getLucky(self, s: str, k: int) -> int: n = "" for c in s: n += str(ord(c) - ord("a") + 1) while k > 0: a = 0 n = str(n) for i in n: a += int(i) n = a k -= 1 return n -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 123.194.160.111 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1725323931.A.3F9.html

09/03 08:40, 1年前 , 1F
別倦了
09/03 08:40, 1F
文章代碼(AID): #1crbgRFv (Marginalman)
討論串 (同標題文章)
文章代碼(AID): #1crbgRFv (Marginalman)