首页 > 技术文章 > Happy Number - LeetCode

fenshen371 2015-10-22 01:32 原文

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: 19 is a happy number

  • 1^2 + 9^2 = 82
  • 8^2 + 2^2 = 68
  • 6^2 + 8^2 = 100
  • 1^2 + 0^2 + 0^2 = 1

思路:给定一个输入后,有两种情况:是或者不是happy number。但是若不是的话,则判断过程会陷入无限循环。

这道题关键就是如何判断处于无限循环中。

这里有一个突破点,就是在判断happy number过程中,如果是无限循环,则循环中会有结果是重复出现的。

思路:设置一个slow变量,设置一个fast变量。然后我们定义一个函数get_sqsum(int n)来计算一个数n的各位数的平方和。

之后,在开始时slow和fast都等于n,然后在程序中我们进行循环,令slow = get_sqsum(slow)。 fast同理,但在每次循环中都进行两次。这相当于两个人在跑道上跑步,fast跑的速度是slow的两倍。因为跑道是圆的(loop),则fast必定会在某个时刻再次遇到slow,这时相当于已经领先了1整圈。

使用do while,循环结束的条件是判断slow是否等于fast。

这里可以看到,不管是否是happy number,slow和fast总有相等的时候。而如果是happy number,则循环结束时两个变量都应该等于1,否则不是。

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

 

推荐阅读