3、快乐数

关键:快慢指针思想  非快乐数的条件 打破循环

若是 1 ,快指针会在1处循环,等慢指针追上;

若不是 1 ,慢指针会在一个周期后追上快指针。

 

 1 class Solution {
 2 public:
 3     int bitSquareSum(int n){
 4         int sum = 0;
 5         while(n>0){
 6             int bit = n%10;
 7             sum = sum + bit*bit;
 8             n = n / 10;
 9         }
10         return sum;
11     }
12 
13     bool isHappy(int n) {
14         int low = n;
15         int fast = n;
16         do{
17             low = bitSquareSum(low);
18             fast = bitSquareSum(fast);
19             fast = bitSquareSum(fast);
20         }while(low!=fast);
21 
22         if(low==1)return true;
23         else return false;
24       
25     }
26 };

 

posted @ 2020-07-05 16:08  Gumpest  阅读(80)  评论(0)    收藏  举报