Created
January 26, 2021 04:48
-
-
Save rafiq/a352e1c860298fecd15ddc0da68dcdbb to your computer and use it in GitHub Desktop.
Help me figure out why the 44 number is not working
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
I have an error with the 44 argument. I think it has something to do with lines 24 to 27 where the logic is getting messed up due to it being such a small string. We may be able to just add another piece of logic to the if statement on line 22, but I am not sure what I would add. | |
I know I can solve this more simply by changing the numbers to a string and comparing the first of the string to the second half of the string, but I chose to use two pointers because it is more robust due to the fact that it can handle all character types which is why I want to use it. | |
INSTRUCTIONS: | |
A double number is an even-length number whose left-side digits are exactly the same as its right-side digits. For example, 44, 3333, 103103, and 7676 are all double numbers, whereas 444, 334433, and 107 are not. | |
Write a function that returns the number provided as an argument multiplied by two, unless the argument is a double number; return double numbers as-is. | |
*/ | |
function twice(num) { | |
if(String(num).length % 2 === 0 && isDoubles(num)) { | |
return num; | |
} else { | |
return num * 2; | |
} | |
} | |
function isDoubles(num) { | |
let numString = String(num); | |
let i = 0; | |
let j = Math.floor(numString.length / 2); | |
while(i < Math.floor(numString.length / 2)) { | |
if(numString[i] !== numString[j] ) { | |
return false; | |
} else { | |
i++; | |
j++; | |
return numString[i] === numString[j]; | |
} | |
} | |
} | |
console.log( | |
twice(37), // 74 | |
twice(44), // 44 | |
twice(334433), // 668866 | |
twice(444), // 888 | |
twice(107), // 214 | |
twice(103103), // 103103 | |
twice(3333), // 3333 | |
twice(7676), // 7676 | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Awesome! Thanks for that info. Very helpful.