Created
April 11, 2025 16:35
-
-
Save tatsuyax25/d4d6bed5dd0202aa2f5c2805e775dd55 to your computer and use it in GitHub Desktop.
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. Re
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param {number} low | |
* @param {number} high | |
* @return {number} | |
*/ | |
// Function to check if a number has an even number of digits | |
function hasEvenDigits(num) { | |
const digitCount = num.toString().length; | |
return digitCount % 2 === 0; // True if the digit count is even | |
} | |
// Function to split a number into two halves and check if they are symmetric | |
function isSymmetric(num) { | |
const numStr = num.toString(); | |
const n = numStr.length / 2; // Half the number of digits | |
const firstHalf = numStr.slice(0, n); // First n digits | |
const secondHalf = numStr.slice(n); // Last n digits | |
// Calculate the sum of each half | |
const sumFirstHalf = firstHalf.split('').reduce((acc, digit) => acc + parseInt(digit), 0); | |
const sumSecondHalf = secondHalf.split('').reduce((acc, digit) => acc + parseInt(digit), 0); | |
return sumFirstHalf === sumSecondHalf; // Check if both sums are equal | |
} | |
// Main function to count symmetric integers in the range [low, high] | |
var countSymmetricIntegers = function(low, high) { | |
let count = 0; // Intialize counter | |
for (let num = low; num <= high; num++) { | |
if (hasEvenDigits(num) && isSymmetric(num)) { | |
count++; // Increment count if the number is symmetric | |
} | |
} | |
return count; // return the total count | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment