leetcode-202 Happy Number

原创 2015年07月07日 15:29:13

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

题意清楚。要注意的是可能陷入无限循环中。因此要注意,记录之前出现的数字,一旦发现重复的,就代表陷入死循环,返回false。
时间8ms。
代码:

class Solution {
public:
    unordered_set<int> hashset;
    bool isHappy(int n) {
        hashset.insert(n);
        int tmp=0;
        while(n > 0)
        {
            int i = n%10;
            n=n/10;
            tmp = tmp + i*i;
        }
        if(1 == tmp)
        return true;
        else
        {
            if(hashset.find(tmp) != hashset.end())
            return false;
            else
            isHappy(tmp);
        }
    }
};
版权声明:本文为博主原创文章,未经博主允许不得转载。

Leetcode_202_Happy Number

本文是在学习中的总结,欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/45396585 Write an algorith...

Happy Number - LeetCode 202

题目描述: Write an algorithm to determine if a number is "happy". A happy number is a number defined...
  • bu_min
  • bu_min
  • 2015年05月20日 20:32
  • 219

<LeetCode OJ> 202. Happy Number

202. Happy Number My Submissions Question Total Accepted: 46878 Total Submissions: 134944 Diffic...

【leetcode】202. Happy Number

一、题目描述 Write an algorithm to determine if a number is "happy". A happy number is a number defined...

Leetcode NO.202 Happy Number

本题题目要求如下: Write an algorithm to determine if a number is "happy". A happy number is a number defi...

LeetCode 202 Happy Number(开心数)(vector、unordered_set)

翻译写一个算法来决定一个数是否是“开心”的。开心数是被如下步骤所定义的数:从所有正整数开始,用其每个数字的平方和来替代这个数,不断重复这个过程直到最后的结果为1(此时它就停止了),或者它在一个不包含1...
  • NoMasp
  • NoMasp
  • 2016年01月19日 10:51
  • 1783

Leetcode 202:Happy Number

Write an algorithm to determine if a number is "happy". A happy number is a number defined by the fo...

[leetcode]202.Happy Number

题目 Write an algorithm to determine if a number is "happy". A happy number is a number define...

Leetcode 202. Happy Number

Write an algorithm to determine if a number is “happy”.A happy number is a number defined by the fol...

leetCode 202. Happy Number

题目链接:https://leetcode.com/problems/happy-number/         题目内容: Write an algorithm to determine...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:leetcode-202 Happy Number
举报原因:
原因补充:

(最多只允许输入30个字)