3461. Check If Digits Are Equal in String After Operations I

題目

You are given a string s consisting of digits. Perform the following operation repeatedly until the string has exactly two digits:

For each pair of consecutive digits in s, starting from the first digit, calculate a new digit as the sum of the two digits modulo 10.

Replace s with the sequence of newly calculated digits, maintaining the order in which they are computed.

Return true if the final two digits in s are the same; otherwise, return false.

題目連結

思路

此題可以使用較為直觀的邏輯來解題,將輸入的字串重複的進行題目所要求的操作,由於每次操作都會讓字串的長度 -1,因此只要持續執行到長度變為 2 時即停止迴圈,最後回傳字串的前後兩位數是否相同即可。

Full Code

class Solution:
    def hasSameDigits(self, s: str) -> bool:
        opStr = s

        while len(opStr) != 2:
            n = len(opStr)
            tmpStr = ""

            for i in range(n - 1):
                tmpStr += str((int(opStr[i]) + int(opStr[i+1])) % 10)

            opStr = tmpStr
        
        return opStr[0] == opStr[1]

Copyright© 2026 ZeoXer. All Rights Reserved.