LeetCode 2843: Count Symmetric Integers (Digit Split / Enumeration)
English
A symmetric integer must have an even number of digits, and the sum of the first half digits must equal the sum of the second half digits. Since high is small enough, we can enumerate each number in [low, high], skip odd-length numbers, then compare the two half sums.
class Solution {
public int countSymmetricIntegers(int low, int high) {
int ans = 0;
for (int x = low; x <= high; x++) {
String s = Integer.toString(x);
int n = s.length();
if ((n & 1) == 1) continue;
int half = n / 2;
int left = 0, right = 0;
for (int i = 0; i < half; i++) {
left += s.charAt(i) - '0';
right += s.charAt(i + half) - '0';
}
if (left == right) ans++;
}
return ans;
}
}class Solution:
def countSymmetricIntegers(self, low: int, high: int) -> int:
ans = 0
for x in range(low, high + 1):
s = str(x)
n = len(s)
if n % 2 == 1:
continue
half = n // 2
left = sum(int(c) for c in s[:half])
right = sum(int(c) for c in s[half:])
if left == right:
ans += 1
return ans中文
对称整数要求位数是偶数,并且前一半数字和等于后一半数字和。由于题目范围不大,可以直接枚举 [low, high] 内每个数,奇数位直接跳过,偶数位就拆成两半比较数字和。
class Solution {
public int countSymmetricIntegers(int low, int high) {
int ans = 0;
for (int x = low; x <= high; x++) {
String s = Integer.toString(x);
int n = s.length();
if ((n & 1) == 1) continue;
int half = n / 2;
int left = 0, right = 0;
for (int i = 0; i < half; i++) {
left += s.charAt(i) - '0';
right += s.charAt(i + half) - '0';
}
if (left == right) ans++;
}
return ans;
}
}class Solution:
def countSymmetricIntegers(self, low: int, high: int) -> int:
ans = 0
for x in range(low, high + 1):
s = str(x)
n = len(s)
if n % 2 == 1:
continue
half = n // 2
left = sum(int(c) for c in s[:half])
right = sum(int(c) for c in s[half:])
if left == right:
ans += 1
return ans