Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Returns true if number is a palindrome, otherwise returns false
- const isPalindrome = (num: number) => {
- // Convert to string so we can analyse the digits easier
- // There is probably a 'mathsy' way to work this out without converting
- let numberAsString = num.toString();
- // i is cursor (pointer) going left to right
- // j is cursor (pointer) going right to left
- let i = 0;
- let j = numberAsString.length;
- // Adding just in case
- if (num < 0) return false;
- // Keep comparing leftmost and rightmost characters at same intervals,
- // from beginning and end of string (originally number) until finished or a non-match is found
- while (i<=j){
- if (numberAsString.substring(i, i + 1) != numberAsString.substring(j - 1, j)){
- return false;
- }
- i++;
- j--;
- }
- return true;
- }
- // Finds a sum of all palindromic numbers,
- // which must be at least as large as the 'target' specified
- // and a palindrome in itself
- // Returns the number of palindromes used to find the sum
- const findSum = (target) => {
- let accumulator = 0;
- let i = 0;
- // Loop continuously until we reach the target
- // Alternatively we could add an upper bound (such as the 'target' itself)
- // to be extra careful of avoiding an infinite loop condition
- while(true){
- if (accumulator > target && isPalindrome(accumulator)) break;
- if (isPalindrome(i)) accumulator += i;
- i++;
- }
- return i;
- }
- // A few quick checks to make sure our function works as expected
- // Should print 'true' for all
- const isPalindrome_test = () => {
- console.log(true === isPalindrome(1231321));
- console.log(true === isPalindrome(171171));
- console.log(true === isPalindrome(11));
- console.log(true === isPalindrome(0));
- console.log(true === isPalindrome(1));
- console.log(true === isPalindrome(123456787654321));
- console.log(false === isPalindrome(522));
- console.log(false === isPalindrome(13213));
- console.log(false === isPalindrome(-25));
- console.log(false === isPalindrome(-131));
- console.log(false === isPalindrome(12333521));
- console.log(false === isPalindrome(1234577654321));
- }
- const findSum_test = () => {
- console.log(findSum(1000000))
- }
- //isPalindrome_test();
- findSum_test();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement