From 4f1407de1c59ca05ea27d5e3eaa02fa7e372dde6 Mon Sep 17 00:00:00 2001 From: Justin Shih Date: Tue, 13 Mar 2018 11:52:30 -0700 Subject: [PATCH] Added solutions to js files --- isNumberPalindrome.js | 16 +++++++++------- longestCommonPrefix.js | 19 +++++++++++++------ 2 files changed, 22 insertions(+), 13 deletions(-) diff --git a/isNumberPalindrome.js b/isNumberPalindrome.js index 699a785..5def57c 100644 --- a/isNumberPalindrome.js +++ b/isNumberPalindrome.js @@ -2,6 +2,7 @@ Make a copy of the original input and assign units digit using modulo and place in reversed version until done, compare the reversed number with the original. If equal, return true. Steps + 1 Copy the input 1331 digit = 1331 % 10 = 1 @@ -21,14 +22,15 @@ Steps number copy = 0 5 1331 = 1331 return true + */ const isNumberPalindrome = (number) => { - // copy input number to build reversed number - // init reversed number and digit - // iterate until copy is 0 or less - // current digit is copy % 10 - // multiply reversed number by 10 and add the digit - // divide the number copy by 10 and remove decimals + let reversedNum = number; // copy input number to build reversed number + let reversed = 0; + let digit = 0;// init reversed number and digit + for (var i = 0; reversedNum <= 0; i++){ // iterate until copy is 0 or less + digit = (reversedNum % 10)// current digit is copy % 10 + reversed = (10 * reversed) + digit// multiply reversed number by 10 and add the digit + reversed = Math.floor(reversed/10)// divide the number copy by 10 and remove decimals } return reversed === number; } - */ diff --git a/longestCommonPrefix.js b/longestCommonPrefix.js index 99bd9f6..90bc745 100644 --- a/longestCommonPrefix.js +++ b/longestCommonPrefix.js @@ -32,10 +32,17 @@ bar "" bar MATCH! continue with next string (prefix is completely gone...) -const longestCommonPrefix = arrayOfStrings => { - // initialize the "longest prefix" with the entire first string - // iterate from the 2nd string onward - // shorten the prefix from the end until there's a match (which is guaranteed when the string - is empty) - }; */ +const longestCommonPrefix = arrayOfStrings => { + let longestCommonPrefix = arrayOfStrings[0];// initialize the "longest prefix" with the entire first string + for (var i = 1; i < arrayOfStrings; i++){// iterate from the 2nd string onward + function comparePrefixAndString() { + if (longestCommonPrefix.indexOf(arrayOfStrings[i]) !== 0) { + longeestCommonPrefix.slice(0, -1); + comparePrefixAndString();// shorten the prefix from the end until there's a match (which is guaranteed when the string is empty) + } else { + return 'MATCH!'; + } + } + } +};