Advertisement
Guest User

Untitled

a guest
Mar 18th, 2018
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Returns true if number is a palindrome, otherwise returns false
  2. const isPalindrome = (num: number) => {
  3.     // Convert to string so we can analyse the digits easier
  4.     // There is probably a 'mathsy' way to work this out without converting
  5.     let numberAsString = num.toString();   
  6.    
  7.     // i is cursor (pointer) going left to right
  8.     // j is cursor (pointer) going right to left
  9.     let i = 0;
  10.     let j = numberAsString.length;
  11.  
  12.     // Adding just in case
  13.     if (num < 0) return false;
  14.  
  15.     // Keep comparing leftmost and rightmost characters at same intervals,
  16.     // from beginning and end of string (originally number) until finished or a non-match is found
  17.     while (i<=j){
  18.         if (numberAsString.substring(i, i + 1) != numberAsString.substring(j - 1, j)){
  19.             return false;
  20.         }
  21.         i++;
  22.         j--;
  23.     }
  24.     return true;   
  25. }
  26.  
  27. // Finds a sum of all palindromic numbers,
  28. // which must be at least as large as the 'target' specified
  29. // and a palindrome in itself
  30. // Returns the number of palindromes used to find the sum
  31. const findSum = (target) => {
  32.     let accumulator = 0;
  33.     let i = 0;
  34.  
  35.     // Loop continuously until we reach the target
  36.     // Alternatively we could add an upper bound (such as the 'target' itself)
  37.     // to be extra careful of avoiding an infinite loop condition
  38.     while(true){
  39.         if (accumulator > target && isPalindrome(accumulator)) break;
  40.         if (isPalindrome(i)) accumulator += i;
  41.         i++;
  42.     }
  43.     return i;
  44. }
  45.  
  46. // A few quick checks to make sure our function works as expected
  47. // Should print 'true' for all
  48. const isPalindrome_test = () => {
  49.     console.log(true === isPalindrome(1231321));
  50.     console.log(true === isPalindrome(171171));
  51.     console.log(true === isPalindrome(11));
  52.     console.log(true === isPalindrome(0));
  53.     console.log(true === isPalindrome(1));
  54.     console.log(true === isPalindrome(123456787654321));
  55.     console.log(false === isPalindrome(522));
  56.     console.log(false === isPalindrome(13213));
  57.     console.log(false === isPalindrome(-25));
  58.     console.log(false === isPalindrome(-131));
  59.     console.log(false === isPalindrome(12333521));
  60.     console.log(false === isPalindrome(1234577654321));
  61. }
  62.  
  63. const findSum_test = () => {
  64.     console.log(findSum(1000000))
  65. }
  66.  
  67.  
  68. //isPalindrome_test();
  69. findSum_test();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement