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;
}


版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

202. Happy Number

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

【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

本文是在学习中的总结,欢迎转载但请注明出处: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...

400. Nth Digit\202. Happy Number\257. Binary Tree Paths

Nth Digit 题目描述 代码实现 Happy Number 题目描述 代码实现400. Nth Digit题目描述Find the nth digit of the infinite integ...

202. Happy Number

Write an algorithm to determine if a number is "happy". A happy number is a number defined by the f...
  • iFuMI
  • iFuMI
  • 2016-03-27 23:58
  • 156

<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...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

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