【LeetCode】 Happy Number 解题报告

来源:互联网 发布:磁力搜索软件 编辑:程序博客网 时间:2024/06/07 06:40

Happy Number

[LeetCode]

https://leetcode.com/problems/happy-number/

Total Accepted: 36352 Total Submissions: 109782 Difficulty: Easy

Question

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.

Examples

Example: 19 is a happy number

12 + 92 = 8282 + 22 = 6862 + 82 = 10012 + 02 + 02 = 1

Ways

方法一

使用递归的方法。

我自己的算法,10以下的Happy Number 只有 1和7 ,

如果一个数计算到只有个位数时,如果计算到十位以下,这个数是1或7,返回true,否则,返回false

public static boolean isHappy2(int n) {    int ans = 0;    if (n == 1 || n == 7) {        return true;    } else if (n > 1 && n < 10) {        return false;    } else {        String numString = "" + n;        char numChar[] = numString.toCharArray();        for (char aNumChar : numChar) {            ans += (aNumChar - '0') * (aNumChar - '0');        }    }    return isHappy2(ans);}

方法一改进:

没必要10以下的数字啊,1到7之间的都是false。直接判断数到1和7之间 就false就好了。

7通过计算也回到1

public static boolean isHappy5(int n) {    int ans = 0;    if (n == 1) {        return true;    } else if (n > 1 && n < 7) {        return false;    } else {        String numString = "" + n;        char numChar[] = numString.toCharArray();        for (char aNumChar : numChar) {            ans += (aNumChar - '0') * (aNumChar - '0');        }    }    return isHappy5(ans);}

方法二

同计算循环小数一样, 如果出现循环, 则无需继续计算,直接返回false即可.

每次计算时,把已经计算数放到一个集合里面,在计算过程中如果出现循环(集合里已经有这个数字),返回false。否则一直计算。

Solution

托管在我的GitHub上:

https://github.com/fuxuemingzhu/HappyNumber

Captures

测试结果截图:

Reference

http://www.jiuzhang.com/solutions/happy-number/

http://blog.csdn.net/xudli/article/details/45267247

Date

2015/10/16 16:06:37

0 0