力扣 202 快乐数
首先来分析什么样的数是快乐数,
解题思路:
1)定义快慢指针 ; 2)快指针走两步,慢指针走一步 ;3)两个指针相遇时判断相遇的数值是否为1。
怎样处理 取各分位数的平方和?
int isSum(int n)
{int sum = 0;//用来记录各分位的平方和while(n !=0){int t = n%10;sum += t*t;n/=10;}return sum;
}
代码实现:
class Solution {
public:int isSum(int n){int sum = 0;while(n !=0){int t = n%10;sum += t*t;n /=10;}return sum;}bool isHappy(int n) {int slow = isSum(n);int fast = isSum(isSum(n));while(fast != slow){fast = isSum(isSum(fast)) ;slow = isSum(slow);}return slow ==1;}
};