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 이하의 범위에 있을 때,
이 범위 내에서 대칭 정수의 개수를 반환하세요.
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.
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이하의 수 중에서 대칭 정수를 찾아야한다.
처음에 일단 대칭정수를 저장할 변수를 지정해준 후, 주어진 범위 내에의 모든 수를 하나씩 확인한다.
그리고 현재 수를 문자열로 바꾼 후에, 자릿수가 홀수라면 건너뛰어준다.