202. 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
1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2 = 1

题目翻译

写一个程序来判断一个数字是否是“开心的”。

一个数字是否开心是由以下的流程来决定的:由一个正整数开始,求它的每个数位的平方和作为新的正整数,然后循环这个过程直至得到的数字为1(此时它会保持),或者它会在非1的数上无限循环。那些最终得到1的数字就是开心数字。

示例1:

19是一个开心数字
1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2 = 1

解题方案

标签: Hash Table、Math

思路:

  • 为了避免循环,这里需要使用Hash Table来记录出现过的数字,一旦循环出现,则返回false值。
  • 其余的数字进行正常计算判断即可,比较简单的一道题。示例代码中给出了调用函数计算n的每一位的平方和的方法,使计算和判断分开了,令代码更加简洁明了。

代码:

class Solution {
    public boolean isHappy(int n) {
        HashSet<Integer> set =new HashSet<>();
        while(n!=1){
            n=squareSum(n);
            if(set.contains(n)) return false;
            set.add(n);
        }
        return true;
    }
    public int squareSum(int n){
        int sum=0;
        while(n>0){
            sum+=(n%10)*(n%10);
            n/=10;
        }
        return sum;
    }
}

参考资料

同步发表于 http://blog.csdn.net/zhning12L/article/details/78276822

results matching ""

    No results matching ""