leetcode 2843

도토코·2025년 4월 14일

알고리즘 문제 풀이

목록 보기
39/44

문제

You are given two positive integers low and high.

An integer x consisting of 2 * n digits is symmetric if the sum of the first n digits of x is equal to the sum of the last n digits of x. Numbers with an odd number of digits are never symmetric.

Return the number of symmetric integers in the range [low, high].

문제 번역

두 개의 양의 정수 low와 high가 주어집니다.

어떤 정수 x가 2 * n 자리수일 때,
앞의 n자리 숫자의 합과 뒤의 n자리 숫자의 합이 같다면 x는 대칭 정수(symmetric integer)라고 합니다.
자릿수가 홀수인 수는 절대 대칭 정수가 될 수 없습니다.

정수 x가 low 이상 high 이하의 범위에 있을 때,
이 범위 내에서 대칭 정수의 개수를 반환하세요.

예시

Example 1:

Input: low = 1, high = 100
Output: 9
Explanation: There are 9 symmetric integers between 1 and 100: 11, 22, 33, 44, 55, 66, 77, 88, and 99.

Example 2:

Input: low = 1200, high = 1230
Output: 4
Explanation: There are 4 symmetric integers between 1200 and 1230: 1203, 1212, 1221, and 1230.


class Solution:
    def countSymmetricIntegers(self, low: int, high: int) -> int:
        cnt = 0
        for n in range(low, high + 1):
            s = str(n)
            if len(s) % 2 != 0:
                continue
            mid = len(s) // 2

            left_sum = 0
            for i in range(mid):
                left_sum += int(s[i])

            right_sum = 0
            for i in range(mid, len(s)):
                right_sum += int(s[i])
            
            if left_sum == right_sum:
                cnt += 1
        return cnt
            

이 문제는 대칭정수를 찾는 문제이다.
low와 high가 주어지면 low이상 high이하의 수 중에서 대칭 정수를 찾아야한다.

대칭정수

  • 짝수 자릿수를 가져야 함
  • 앞 절반과 뒷 절반의 각 자리 숫자의 합이 같아야 함.

처음에 일단 대칭정수를 저장할 변수를 지정해준 후, 주어진 범위 내에의 모든 수를 하나씩 확인한다.
그리고 현재 수를 문자열로 바꾼 후에, 자릿수가 홀수라면 건너뛰어준다.

profile
코(딩)(꿈)나무

0개의 댓글