Happy Number

来源:互联网 发布:内容营销的出路 知乎 编辑:程序博客网 时间:2024/06/17 14:59

Write an algorithm to determine if a number is “happy”.

A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.

Example: 19 is a happy number


解题思路:
本人的思路就是递归计算数字各个位数的平方和,并存储与map哈希表中,若为1返回true,若在map中有重复的出现的情况,则返回false。以下是我个人代码,效率不高,有好的建议请留言!谢谢

 function square(n){return n*n;}// function sumResult(map,n)//     {//      var sum=0;//       while(Math.floor(n/10))//         {//             sum += square(n%10);//             n = Math.floor(n/10);//         }//         sum += square(n%10);//         if(sum===1)//         {//             return true;//         }else if(map.hasOwnProperty(sum)){//           return false;//         }else{//             map[sum] = sum;//         }//       return sumResult(map,sum);//     }var isHappy = function(n) {    var sum=n,         m = n,        map = {};        map[n] = n;    if(n===1)    {        return true;    }else if(n===0)    {        return false;    }   while(sum!==1)   {      sum=0;      while(Math.floor(n/10))//取出n的各个位        {            sum += square(n%10);//对n的各个位上的数字求平方            n = Math.floor(n/10);//移位        }        sum += square(n%10);        if(sum===1)        {            return true;        }else if(map.hasOwnProperty(sum)){          return false;        }else{            map[sum] = sum;        }        n=sum;   }    return true;};
0 0
原创粉丝点击