지난 공부기록/알고리즘 풀이

Python - Algorithm #38

hkl22 2024. 8. 23. 10:19

Python Algorithm

LeetCode

258. Add Digits

  • Given an integer num, repeatedly add all its digits until the result has only one digit, and return it.
  • Constraints
    • 0 num 2³¹ - 1
class Solution:
    def addDigits(self, num: int) -> int:
        # while문, 숫자 -> 문자열 -> 숫자
        while num >= 10:
            # 각 자릿수의 합계를 num에다가 입력
            digit_sum = 0
            for c in str(num):
                digit_sum += int(c)
            num = digit_sum
        return num
class Solution:
    def addDigits(self, num: int) -> int:
        while num >= 10:
            num = sum([int(c) for c in str(num)])
        return num
class Solution:
    def addDigits(self, num: int) -> int:
        s = str(num)
        while True:
            sum_ = 0
            for i in range(len(s)):
                sum_ += int(s[i])
            s = str(sum_)
            if len(s) == 1:
                break
        return int(s)

3174. Clear Digits

  • You are given a string s.
  • Your task is to remove all digits by doing this operation repeatedly:
    • Delete the first digit and the closest non-digit character to its left.
  • Return the resulting string after removing all digits.
  • Constraints
    • 1 s.length 100
    • s consists only of lowercase English letters and digits.
    • The input is generated such that it is possible to delete all digits.
class Solution:
    def clearDigits(self, s: str) -> str:
        # while, 숫자를 지울 수 있는 조건 잘 살펴보기
        while s:
            flag = False
            # 첫 번째 숫자 찾아서 제거
            # 숫자 제거, 문자열 slicing 활용
            # 3번째 위치한 문자를 제거
            # s = s[:3] + s[4:]
            for i, c in enumerate(s):
                if c.isnumeric():
                    flag = True
                    if i == 0:
                        s = s[i+1:]
                    else:
                        s = s[:i-1] + s[i+1:]
                    break
            if not flag:
                break
        return s
class Solution:
    def clearDigits(self, s: str) -> str:
        answer = []
        for i in s:
            if i.isdigit():
                answer.pop()
            else:
                answer.append(i)
        return "".join(answer)

https://leetcode.com/problems/add-digits/

https://leetcode.com/problems/clear-digits/

'지난 공부기록 > 알고리즘 풀이' 카테고리의 다른 글

Python - Algorithm #40  (0) 2024.08.27
Python - Algorithm #39  (0) 2024.08.26
Python - Algorithm #37  (0) 2024.08.12
Python - Algorithm #36  (0) 2024.08.09
Python - Algorithm #35  (0) 2024.08.08