LeetCode Happy Number

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode Happy Number相关的知识,希望对你有一定的参考价值。

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

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

Credits:
Special thanks to @mithmatt and @ts for adding this problem and creating all test cases.

题目:让你判断一个数是否是开心数。一个正数,用它的数字的平方和来代替他,如果有结果等于1,则就是一个开心数。如果一个数一直无限循环还是得不到1,

那么就不是开心数。

这个题目要建立一个hash表,来判断是否无限循环。

 

class Solution {
public:
   
    bool isHappy(int n) {
        map<int, int> intMap;
        int sum;
        while(1)
        {
            sum = 0;
            while (n >= 10)
            {
                sum += (n % 10)*(n % 10);
                n = n / 10;
            }
            sum += n*n;
            if (1 == sum)return true;
            else n = sum;
            if (intMap.find(n) == intMap.end())
                intMap[n] = 1;
            else break;
        }
        return false;
    }
};

 

以上是关于LeetCode Happy Number的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode-Happy Number

leetcode 202. Happy Number

LeetCode----202. Happy Number(Java)

[LeetCode][JavaScript]Happy Number

40. leetcode 202. Happy Number

leetCode(29):Happy Number