[LeetCode] Count Symmetric Integers

2843. Count Symmetric Integers

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
bool ok(string s) {
if(s.length() % 2) return false;
int l = 0, r = s.length() - 1;
int lsum = 0, rsum = 0;
while(l < r) {
lsum += s[l] - '0';
rsum += s[r] - '0';
l += 1, r -= 1;
}
return lsum == rsum;
}
public:
int countSymmetricIntegers(int low, int high) {
int res = 0;
for(int i = low; i <= high; i++) {
string s = to_string(i);
if(ok(s)) res += 1;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/09/03/PS/LeetCode/count-symmetric-integers/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.