Leetcode202-Happy Number

来源:互联网 发布:小米k歌软件 编辑:程序博客网 时间:2024/06/05 19:18

Leetcode202-Happy Number(Easy)

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.


题意:

happy数的定义如下:给定一个正整数,用其各位数的平方和取代该数,重复此操作直到该数等于1,或形成一个不为1的循环。其中,前者成为happy数。

例子:
1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2 = 1


分析:

题目中已经给了提示,当能出现1时,即退出循环返回true;如出现了一个不为1的循环则返回false(如4, 16, 37, 58, 89, 145, 42, 20, 4, ...)。对happy number的详细描述见wiki百科:Happy Number。wiki还对Happy primes和Harshad number做了一些解释。为了快速确定是否发生非1的重复,使用unordered_set来记录已经出现过的数(我们并不关心数字的顺序,因此用hash效率更高)。


AC代码:

class Solution {public:    bool isHappy(int n) {        int sum;        unordered_set<int> check;        check.insert(n);        while (n != 1) {        sum = 0;        while (n) {        int t = n % 10;        n /= 10;        sum += t * t;        }        if (check.find(sum) != check.end())        return false;        check.insert(sum);        n = sum;        }        return true;    }};
如代码或分析有误,请批评指正,谢谢。

0 0
原创粉丝点击