Created
August 25, 2014 20:13
-
-
Save heyitsjames/ad166e9bc0e8ab363e3a to your computer and use it in GitHub Desktop.
isHappy?
This file contains hidden or 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
| Write a function called isHappy that takes a number as a parameter, and determines whether or not that number is "happy," returning true or false. | |
| How to determine if a number is happy: | |
| 7 is happy | |
| -> 7x7 = 49 | |
| -> 4x4 + 9x9 = 97 | |
| -> 9x9 + 7x7 = 81+49 = 130 | |
| -> 1x1 + 3x3 + 0x0 = 10 | |
| -> 1x1 + 0x0 = 1 => true | |
| An example sad number is 2: | |
| -> 2x2 = 4 | |
| -> 4x4 = 16 | |
| -> 1x1 + 6x6 = 37 | |
| -> 3x3 + 7x7 = 58 | |
| -> 5x5 + 8x8 = 89 | |
| -> 8x8 + 9x9 = 145 | |
| -> 1x1 + 4x4 + 5x5 = 42 | |
| -> 4x4 + 2x2 = 20 | |
| -> 2x2 + 0x0 = 4 => false | |
| If the algorithm reaches a sum that is 1, the number is happy. | |
| If it finds a sum that it's already found, the number is sad. |
Author
function isHappy(num) { // num is integer and >= 0. bool
var alreadyChecked = {};
while(typeof alreadyChecked[num] === "undefined") {
var numArray = num.toString().split("");
var sum = 0;
for(var i = 0; i < numArray.length; i++) {
sum += numArray[i] * numArray[i];
}
if(sum === 1) {
return true;
}
else {
alreadyChecked[num] = num;
num = sum;
}
}
return false;
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
public static bool ishappy(int num)
{
List seen = new List();
seen.Add(num);