标签:int sum number 平方和 process happy
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.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/happy-number
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
这道题的难点我觉得就是,当各个数字的平方和sum不等于1时,不能直接退出。但是继续循环下去的时候又容易进入了一个死循环,因此,我们可以设置一个set来存储出现过的平方和,当新算出来的平方和已经存在于此集合时,证明即将进入死循环,所以可以返回false,如果此平方和未曾出现过时,继续判断,同时把此数添加至set里面,并且把n更新为sum.
代码如下:
class Solution { public boolean isHappy(int n) { Set<Integer> temp = new HashSet<>(); while(true) { int sum = 0; while(n != 0) { int m = n % 10; sum += m * m; n /= 10; } if(sum == 1) { return true; } else if(temp.contains(sum)) { return false; } else { temp.add(sum); n= sum; } } } }
标签:int,sum,number,平方和,process,happy 来源: https://www.cnblogs.com/WakingShaw/p/11853951.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。