标签:10 202 sum number Number set 82 平方和 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.
Example:
Input: 19 Output: true Explanation: 12 + 92 = 82 82 + 22 = 68 62 + 82 = 100 12 + 02 + 02 = 1
题目大意:
给定正整数,按照示例方式用它每个数的平方和替代它,若平方和等于1则该正整数为快乐数;若一直无限循环则非快乐数。
理 解:
对于正整数n,n%10从后往前遍历它每一个数,n = n/10删除已遍历的数,sum表示平方和,若sum=1,则n为快乐数;否则,n = sum重新计算平方和。
用集合set判断是否存在循环,每计算一个数,就保存在set中,若s.count(n)不等于0表明已经计算过该数,出现了循环,n为非快乐数。
代 码 C++:
class Solution { public: bool isHappy(int n) { int sum = 0; set<int> s; while(n!=1){ s.insert(n); while(n!=0){ sum += (n%10)*(n%10); n = n/10; } n = sum; if(s.count(n)!=0) return false; sum = 0; } return true; } };
运行结果:
执行用时 :4 ms, 在所有C++提交中击败了97.12%的用户
内存消耗 :8.5 MB, 在所有C++提交中击败了11.41%的用户标签:10,202,sum,number,Number,set,82,平方和,Happy 来源: https://www.cnblogs.com/lpomeloz/p/11014303.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。