202. Happy Number

原创 2016年05月30日 21:52:40


1.我的答案

这里我假设输入最大值为 2147483647, 则10位的数字经过计算后也不过810,因此我开辟811的数组来存。

class Solution {
public:
    int isH(int n, vector<int>& num){
    int sum = 0;
    while(n){
        int yu = n % 10;
        sum += yu*yu;
        n = n / 10;
    }
    return sum;
}
bool isHappy(int n) {
    vector<int>num(811,0);
    int res = n;
    while(1){
        res = isH(res, num);
        if(num[res] !=0)
        return false;
        if(res - 1 == 0)
        return true;
        num[res] = 1;
    }
    return false;
}
};



2.别人的答案 用了快慢指针。 当有环时,slow==fast; 当无环时,fast会先到1,则可以判断出。

   int digitSquareSum(int n) {
        int sum = 0, tmp;
        while (n) {
            tmp = n % 10;
            sum += tmp * tmp;
            n /= 10;
        }
        return sum;
    }

    bool isHappy(int n) {
        int slow, fast;
        slow = fast = n;
        do {
            slow = digitSquareSum(slow);
            fast = digitSquareSum(fast);
            fast = digitSquareSum(fast);
            if(fast == 1) return 1;
        } while(slow != fast);
         return 0;
}


【LeetCode-面试算法经典-Java实现】【202-Happy Number(开心数字)】

【202-Happy Number(开心数字)】【LeetCode-面试算法经典-Java实现】【所有题目目录索引】代码下载【https://github.com/Wang-Jun-Chao】原题  ...

leetcode 202 Happy Number

202. Happy Number Write an algorithm to determine if a number is "happy". A happy number is a num...

【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
  • 1782

202. Happy Number (tortoise and the hare algorithm)

Floyd's Tortoise and Hare-202 Happy Number

202. Happy Number [easy] (Python)

题目链接https://leetcode.com/problems/happy-number/题目原文 Write an algorithm to determine if a number is...

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...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:202. Happy Number
举报原因:
原因补充:

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