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
- Happy Number
- Happy Number
- Happy Number
- Happy number
- Happy Number
- Happy Number
- Happy Number
- Happy Number
- Happy Number
- Happy Number
- Happy Number
- Happy Number
- Happy Number
- Happy Number
- Happy Number
- Happy Number
- Happy Number
- Happy Number
- 下拉选择菜单封装
- Quartz教程三:Job与JobDetail介绍
- 增加机房页面需求之问题汇总
- 遍历js中对象的属性和值
- css position属性
- Happy Number
- Electricity_toj2299_割点
- leetcode——Maximum Product Subarray
- 个人经验积累(纯碎随手记,持续更新)
- 一、Hadoop 2.x 分布式安装部署
- 编写C程序测试整型变量中有多少个1
- Quartz教程四:Trigger
- Javassist library is missing in classpath! Please add missed dependency!
- leetcode 28: Merge Intervals