赞
踩
主要是用到了鸽巢原理,最后他们一定会重合,我们只需要判断类似,链表的成环相遇的时候是不是1就行了
- class Solution {
- public:
-
- int bitsum(int n)
- {
- int sum = 0;
- while (n)
- {
- int a = 0;
- a = n % 10;
- sum += a * a;
- n /= 10;
- }
- return sum;
- }
- bool isHappy(int n) {
- int fast = bitsum(n);
- int slow = n;
- while (fast != slow)
- {
- fast = bitsum(fast);
- fast = bitsum(fast);
- slow = bitsum(slow);
- }
- if (fast == 1)
- {
- return true;
- }
- else return false;
- }
- };
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。