LeetCode 202. Happy Number

来源:互联网 发布:萨勒曼 知乎 编辑:程序博客网 时间:2024/06/07 09:40

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


题目思路:

第一种方法,通过递归一只算下去,用数组记录已经出现的数字,如果在递归过程中算出的数字是重复,那么就结束递归过程。然后判断元素1是否出现即可。

第二种方法,是快慢指针判断链表是否存在环。引申过来如果快慢指针相遇,判断是否是1即可。


题目代码:

class Solution {public:    int vis[999] = {0};    bool isHappy(int n) {        int t = 0;        while(n){            t += (n%10) * (n%10);            n/=10;        }        dfs(t);        if(vis[1])            return true;        return false;    }    void dfs(int n){        int res = 0;        while(n){            res += (n%10) * (n%10);            n/=10;        }        if(vis[res]){            return ;        }        vis[res] = 1;        dfs(res);    }};
class Solution {public:    bool isHappy(int n) {        int pf, ps;        ps = num(n);        pf = num(ps);        while(pf != ps){            ps = num(ps);            pf = num(pf);            pf = num(pf);        }        return ps == 1;    }    int num(int n){        int res = 0;        while(n){            res += (n%10)*(n%10);            n /= 10;        }        return res;    }  };


原创粉丝点击