LeetCode 2843. Count Symmetric Integers Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
2843. Count Symmetric Integers

Description

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].

 

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.

 

Constraints:

  • 1 <= low <= high <= 104

Solutions

Solution 1: Enumeration

We enumerate each integer x in the range [low, high], and check whether it is a palindromic number. If it is, then the answer ans is increased by 1.

The time complexity is O(n × log m), and the space complexity is O(log m). Here, n is the number of integers in the range [low, high], and m is the maximum integer given in the problem.

PythonJavaC++GoTypeScriptRustC#
class Solution: def countSymmetricIntegers(self, low: int, high: int) -> int: def f(x: int) -> bool: s = str(x) if len(s) & 1: return False n = len(s) // 2 return sum(map(int, s[:n])) == sum(map(int, s[n:])) return sum(f(x) for x in range(low, high + 1))(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !