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: Math
- Time complexity: O(high-low)
- Space complexity: O(1)
JavaScript
js
/**
* @param {number} low
* @param {number} high
* @return {number}
*/
const countSymmetricIntegers = function (low, high) {
let result = 0;
const isSymmetric = num => {
if (num < 10) return false;
if (num < 100) return num % 10 === Math.floor(num / 10);
if (num < 1000) return false;
const left = Math.floor(num / 100);
const right = num % 100;
const leftSum = (left % 10) + Math.floor(left / 10);
const rightSum = (right % 10) + Math.floor(right / 10);
return leftSum === rightSum;
};
for (let num = low; num <= high; num++) {
if (!isSymmetric(num)) continue;
result += 1;
}
return result;
};