Javascript Happy Numbers Not Working
Solution 1:
When you recurse, you need to return
the value returned:
if (newNum === 1) {
returntrue;
} else {
return happyChecker(newNum);
}
You also should declare "num" with var
.
I'm ordinarily not a "code golfer", but this is a good example of how the (new-ish) iterator utility methods on the Array prototype can clean up code. You can use the .reduce()
function to traverse the array of digit characters and do the work of squaring and summing all at once:
var newNum = n.toString()
.split('')
.reduce(function(sum, digit) {
returnsum + (+digit * +digit);
}, 0);
The call to .toString()
returns a string, then .split('')
gives you an array. Then .reduce()
starts with an initial sum of 0 and for each element of the array (each digit), it adds to it the square of that digit. (Instead of parseInt()
I just used the +
unary operator; we know for sure that each string will be a valid number and an integer.)
Solution 2:
You need to add return to the happyChecker call.
return happyChecker(newNum);
see:
Solution 3:
here is my implementation
var getSum = function (n) {
if (!n >= 0) return -1;
var digits = n.toString().split("");
var sum = 0;
for (var i = 0; i < digits.length; i++) {
var digit = parseInt(digits[i], 10);
sum += digit * digit;
}
return sum;
}
/**
* @param {number} n
* @return {boolean}
*/var isHappy = function(n, visited) {
if (n < 0) returnfalse;
if (n === 1) returntrue;
if (typeof visited === 'undefined') visited = {};
sum = getSum(n);
if (visited[sum]) returnfalse; // cycle
visited[sum] = true;
returnisHappy(sum, visited);
};
Solution 4:
Complete Example of finding happy numbers in range of custom number.
functionhappyNumbers() {
var result = document.getElementById("happy-result")
var inputy = parseInt(document.getElementById("happyValue").value)
result.innerHTML=""for (i = 1; i < inputy; i++) {
(happy(i, i))
}
}
functionhappy(value,value2) {
var result = document.getElementById("happy-result")
var lengthNum = value.toString().length;
var resultNumbers = 0for (var b = 0 ; b < lengthNum; b++) {
resultNumbers = resultNumbers + parseInt(value.toString().charAt(b)) * parseInt(value.toString().charAt(b))
}
if (resultNumbers == 4) {
returnfalse
} elseif (resultNumbers == 1) {
result.innerHTML += "<br> happy number " + i
returntrue
}else{
happy(resultNumbers, value2);
}
}
window.onload=happyNumbers()
<linkrel="stylesheet"href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"><divclass="panel panel-default"><divclass="panel-heading">happy numbers</div><divclass="panel-body"><label>Enter the number that you want ot have see happy numbers uo to it</label><inputid="happyValue"oninput="happyNumbers()"value="100"class="form-control" /><divid="happy-result"></div></div></div>
Post a Comment for "Javascript Happy Numbers Not Working"