Tuesday, June 7, 2016

a/A Practice Problems: Palindrome

We have made it to the last of the "easy" problems. Rejoice!  Here we go...

Write a method that takes a string and returns true if it is a palindrome. A palindrome is a string that is the same whether written backward or forward. Assume that there are no spaces; only lowercase letters will be given.

 We know that we need a function that will take in a single parameter. We also want to declare an empty string that we can use to store the new word we will form by running a loop adding each letter from the string in reverse order. Lastly, we need a check to see if the original and the new string are the same, a palindrome, and return either true or false. Easy peasy.

1. Construct your function.

function palindrome(string) {
}


2. I declared a string that would hold the index position of the last letter of the string so as to use the variable in the loop instead. This isn't necessary. But you will want to declare a variable newString, which will be the original string in reversed order.

function palindrome(string) {
   var lastIndex = string.length - 1;
   var newString = "";
}


3. The loop starts with the index of the last letter, lastIndex, which we defined previously. It will continue so long as i is greater than or equal to 0, and will decrease by one each time. The code block inside the loop will concatenate each letter and form the new string in newString.

function palindrome(string) {
   var lastIndex = string.length - 1;
   var newString = "";
   for (var i = lastIndex; i >= 0; i--) {
      newString += string[i];
   }
}


 4. Lastly, an if statement that says if the original string and newString are the same will return true, else it will return false.

function palindrome(string) {
   var lastIndex = string.length - 1;
   var newString = "";
   for (var i = lastIndex; i >= 0; i--) {
      newString += string[i];
   }
   if (string === newString) {
      return true;
   } else {
      return false;
   }
}


Next up the mediums! **tingles**

Check out past problems here:

No comments :

Post a Comment