码迷,mamicode.com
首页 > 移动开发 > 详细

[LeetCode] Happy Number

时间:2015-08-17 00:51:01      阅读:207      评论:0      收藏:0      [点我收藏+]

标签:

Well, no matter whether the number is happy or not, its sum-of-squared-digits sequance has a cycle. Well, do you still remember the algorithm for detecting cycles in linked lists? Yeah, use a fast and a slow pointer. That‘s also applicable to this problem.

The code is as follows (idea from here).

 1 class Solution {
 2 public:
 3     bool isHappy(int n) {
 4         int slow = n, fast = n;
 5         do {
 6             slow = squareDigits(slow);
 7             fast = squareDigits(squareDigits(fast));
 8         } while (slow != fast);
 9         return fast == 1;
10     }
11 private:
12     int squareDigits(int n) {
13         int sq = 0;
14         while (n) {
15             sq += (n % 10) * (n % 10);
16             n /= 10;
17         }
18         return sq;
19     }
20 };

 

[LeetCode] Happy Number

标签:

原文地址:http://www.cnblogs.com/jcliBlogger/p/4735358.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!