How to write palindrome in JavaScript

前端 未结 30 1812
情书的邮戳
情书的邮戳 2020-11-29 02:42

I wonder how to write palindrome in javascript, where I input different words and program shows if word is palindrome or not. For example word noon is palindrome, while bad

30条回答
  •  盖世英雄少女心
    2020-11-29 03:36

    Faster Way:

    -Compute half the way in loop.

    -Store length of the word in a variable instead of calculating every time.

    EDIT: Store word length/2 in a temporary variable as not to calculate every time in the loop as pointed out by (mvw) .

    function isPalindrome(word){
       var i,wLength = word.length-1,wLengthToCompare = wLength/2;
    
       for (i = 0; i <= wLengthToCompare ; i++) {
         if (word.charAt(i) != word.charAt(wLength-i)) {
            return false;
         }
       }
       return true;
    } 
    

提交回复
热议问题