Search code examples
javascriptarraysfunctionpalindrome

Return the sum of all palindromic numbers in an array


I'm trying to get the sum of the palindrome numbers in an array with javascript

The code gets outputs 0 instead of getting the sum of palindrome values:

function reverse(n) {
    var rem, res = 0
    while (n > 0) {
        rem = n % 10
        res = res * 10 + rem
        n = n / 10
    }
    return res
}

function isPalindrome(n) {
    if (n == reverse(n)) return true
}

function sumArray(arr) {
    var sum = 0
    for (var i = 0; i < arr.length; i++) {
        if (arr[i] > 10 && isPalindrome(arr[i])) {
            sum += arr[i]
        }
        
    }
    console.log(sum);    
}


sumArray([12, 313, 11, 44, 9, 1])


Solution

  • The issue lies inside your reverse() function. n = n / 10 is leaving some messy decimals behind causing the loop to not terminate.

    while (n > 0) {
        rem = n % 10
        res = res * 10 + rem
        n = n / 10
    }
    

    Just rounding off this result causes your code to run as expected.

    while (n > 0) {
        rem = n % 10
        res = res * 10 + rem
        n = Math.round(n / 10)
    }
    

    Below is the code with that rounding change

      function reverse(n) {
        var rem, res = 0
        while (n > 0) {
          rem = n % 10
          res = res * 10 + rem
          n = Math.round(n / 10)
        }
        return res
      }
    
      function isPalindrome(n) {
        if (n == reverse(n)) return true
      }
    
      function sumArray(arr) {
        var sum = 0
        for (var i = 0; i < arr.length; i++) {
          if (arr[i] > 10 && isPalindrome(arr[i])) {
            sum += arr[i]
          }
    
        }
        console.log(sum);
      }
    
      sumArray([12, 313, 11, 44, 9, 1])