herrDeng網內搜尋

自訂搜尋

Ads

2024年9月3日 星期二

python C++速解Leetcode 1945 Sum of Digits of String After Convert


python C++速解Leetcode 1945  Sum of Digits of String After Convert
這是個簡單問題,有技巧。
第一次轉換不需要用bigINT來存,只是將數字與第1輪的數字相加即可。
由於s.length最多可能為100,因此使用bigInt或其他字串效率非常低。
[Python code請進]
---
This is an easy question with some tricks.
The first conversion does not need to use a bigINT to hold, but just add the digits to the number in the 1st round.
Since s.length may be 100 at most, it's very inefficient to use bigInt or other string.

class Solution:
    def getLucky(self, s: str, k: int) -> int:
        num=0
        for c in s:
            x=ord(c)-96
            q,r =divmod(x, 10)
            num+=q+r
        k-=1
        x=num
        for _ in range(k, 0, -1):
            num=0
            while x>0:
                q,r =divmod(x, 10)
                num+=r
                x=q
            x=num
            if x<10:break
        return num

沒有留言:

Related Posts Plugin for WordPress, Blogger...

熱門文章