DEV Community

michael-2509
michael-2509

Posted on

Palindrome

QUESTION
Given an integer x, return true if x is palindrome integer.

An integer is a palindrome when it reads the same backward as forward.

For example, 121 is a palindrome while 123 is not.

STEP

  • Reverse Integer

  • Compare integer and reversed integer

CODE

  • Reverse Integer

The integer x is converted to a string using toString() method and a for loop is applied to convert the string to it's reverse state using the decrementing for loop

//convert interger to string
  var str = x.toString()

//reverse string
 let reverseStr = ""
    for(condition){
       //logic to reverse string
    }
Enter fullscreen mode Exit fullscreen mode
  • Compare integer and reversed integer string

The condition statement if else was used to compare interger x and the reversed string str using type coercion, otherwise the condition would return false even if it's a palindrome number.

Type coercion helps convert one value type to another which make is it easy to compare values of difference types. Since I'm comparing a string and an interger, I used loose equality == which makes use of type coercion. In this case, string is coerced to an integer before comparism

//loose equality(using type coercion)
123 == "123" -> true
// strict comparis
123 === "123" -> false`
Enter fullscreen mode Exit fullscreen mode
if(condition) {
        return true 
    } else{
        return false
    }
Enter fullscreen mode Exit fullscreen mode

Final Run

var isPalindrome = function(x) {
    //convert interger to string
    var str = x.toString()

    //reverse string
    //var reverseStr = str.split("").reverse().join("")
    let reverseStr = ""
    for(condition){
       //logic to reverse string
    }

    //check for palindrome
  if(condition) {
        return true 
    } else{
        return false
    }
};

Enter fullscreen mode Exit fullscreen mode

Top comments (0)