Javascript Happy Numbers无效

时间:2014-01-24 15:56:17

标签: javascript math

此处我有一个功能,应该在n中加上disHappy(n)来检查是否全部为 n in [n-0)很高兴。

Happy Numbers wikipedia

如果我只运行happyChecker(n),我可以说7很开心,但disHappy(n)没有显示。就好像它没有收到真实的。我在所有地方使用了console.log()'s,happyChecker(n)显示了一个应该返回true的数字。当我在console.log() return true;之上放置if(newNum===1)时,它显示它已分支到该分支,但它似乎没有返回真实。

  function happyChecker(n) {
     var arr = [];
     var newNum = 0;
     //here I split a number into a string then into an array of strings//
     num = n.toString().split("");
     for (var i = 0; i < num.length; i++) {
         arr[i] = parseInt(num[i], 10);
     }
     //here I square each number then add it to newNum//
     for (var i = 0; i < arr.length; i++) {
         newNum += Math.pow(arr[i], 2);
     }
     //here I noticed that all unhappy numbers eventually came into one of these three//
     //( and more) numbers, so I chose them to shorten the checking. A temporary solution for sure//       
     if (newNum === 58 || newNum === 4 || newNum == 37) {
         return false;
     }

     if (newNum === 1) {

         return true;
     } else {
         happyChecker(newNum);
     }

 }

 function disHappy(num) {
     for (j = num; j > 0; j--) {
         if (happyChecker(j)) {
             console.log(j + " is a Happy Number. It's so happy!!!.");
         }
     }
  }

4 个答案:

答案 0 :(得分:4)

当您递归时,您需要return返回的值:

 if (newNum === 1) {

     return true;
 } else {
     return happyChecker(newNum);
 }

您还应该使用var声明“num”。

我通常不是“代码高尔夫球手”,但这是一个很好的例子,说明了Array原型上的(new-ish)迭代器实用程序方法如何清理代码。您可以使用.reduce()函数遍历数字字符数组,并一次完成平方和求和的工作:

var newNum = n.toString()
              .split('')
              .reduce(function(sum, digit) {
                return sum + (+digit * +digit);
               }, 0);

.toString()的调用返回一个字符串,然后.split('')为您提供一个数组。然后.reduce()以0的初始和开始,对于数组的每个元素(每个数字),它将该数字的平方加上。 (而不是parseInt()我只使用+一元运算符;我们确定每个字符串都是有效数字和整数。)

答案 1 :(得分:1)

您需要将return添加到happyChecker调用。

return happyChecker(newNum);

请参阅:

http://jsfiddle.net/YjgL8/2/

答案 2 :(得分:0)

这是我的实现

&#13;
&#13;
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) return false;
    if (n === 1) return true;
    if (typeof visited === 'undefined') visited = {};
    sum = getSum(n);
    if (visited[sum]) return false; // cycle
    visited[sum] = true;
    return isHappy(sum, visited);
};
&#13;
&#13;
&#13;

答案 3 :(得分:0)

在自定义数字范围内找到满意数字的完整示例。

        function happyNumbers() {
            var result = document.getElementById("happy-result")
            var inputy = parseInt(document.getElementById("happyValue").value)
            result.innerHTML=""
            for (i = 1; i < inputy; i++) {

               (happy(i, i)) 
                 
            }

        }

        function happy(value,value2) {
            var result = document.getElementById("happy-result")
            var lengthNum = value.toString().length;
            var resultNumbers = 0

            for (var b = 0 ; b < lengthNum; b++) {

                resultNumbers = resultNumbers + parseInt(value.toString().charAt(b)) * parseInt(value.toString().charAt(b))

            }
           
            if (resultNumbers == 4) {
                return false
            } else if (resultNumbers == 1) {
                result.innerHTML += "<br> happy number  " + i
                return true
            }else{
                happy(resultNumbers, value2);
            }

        }
        
        window.onload=happyNumbers()
     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">   
      <div class="panel panel-default">
            <div class="panel-heading">happy numbers</div>
            <div class="panel-body">
                <label>Enter the number that you want ot have see happy numbers uo to it</label>
                <input id="happyValue" oninput="happyNumbers()" value="100" class="form-control" />
                <div id="happy-result"></div>
            </div>
        </div>