Happy Number

update May 6,2018 14:32

LeetCode

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:

Input: 19
Output: true

Explanation:

12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1

Basic Idea:

这道题的精髓是掌握其中的规律。Pattern 一共有两种,第一种最终会变为 1,就是题目要求的pattern,而另一种是循环的,其中一定会有 4 出现。于是我们只要循环计算平方和,直到 1 和 4 出现即可。

  • C++Code

      class Solution {
      public:
          bool isHappy(int n) {
              while (n != 1 && n != 4) {
                  int t = 0;
                  while (n > 0) {
                      t += pow(n % 10, 2);
                      n /= 10;
                  }
                  n = t;
                  cout << n << endl;
              }
              return n == 1;
          }
      };
    

results matching ""

    No results matching ""