LeetCode: Super Palindromes Solution
1/**2 * @param {string} left3 * @param {string} right4 * @return {number}5 */6var superpalindromesInRange = function (left, right) {7 ;[left, right] = [+left, +right]89 const isPalindrome = s => s === s.split("").reverse().join("")1011 let palindromes = [1, 2, 3, 4, 5, 6, 7, 8, 9]12 // as range is max of 1e18 => find from sqrt(1e18) = 1e913 // build palindrome from concatnate: xx, x0x, x1x,...x9x14 // so x must be in range 9/2 = 415 for (let i = 1; i < 10000; i++) {16 const s1 = String(i) + String(i).split("").reverse().join("")17 palindromes.push(s1)18 for (let j = 0; j < 10; j++) {19 const s2 = String(i) + String(j) + String(i).split("").reverse().join("")20 palindromes.push(s2)21 }22 }2324 palindromes = palindromes.map(Number).sort((a, b) => a - b)2526 let numberOfSuperPalindromesInRange = 02728 for (const palindrome of palindromes) {29 const s = String(BigInt(palindrome) ** 2n)30 if (isPalindrome(s) && left <= Number(s) && Number(s) <= right) {31 numberOfSuperPalindromesInRange++32 }33 }3435 return numberOfSuperPalindromesInRange36}
Comments
Loading comments...
Tags
leetcode
math
string
array
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.