LeetCode(202): Happy Number

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,则是Happy Number返回True,否则程序可能从某个数开始陷入循环。

思路:用一个数组保存已经计算出的结果,如果新的计算结果为1则返回True,如果不为1,且在数组中出现则返回False,否则将新的结果加入到数组中去,继续循环下去。

代码:

//获得n的个位数平方和 
public int get_square_of_digits(int n){
        int result = 0;
        while(n>0){
            result = result + (n%10) * (n%10);
            n=n/10;
        }
        return result;
    }
    
 
 
    public boolean isHappy(int n) {
        if(n==0) return false;
        if(n==1) return true;
        List a= new ArrayList<Integer>();
            
        while(n!=1){
                n = get_square_of_digits(n);
                if(a.contains(n)){
                    return false;
                }else{
                    a.add(n);
                }
            }
            return true;
    }
原文地址:https://www.cnblogs.com/Lewisr/p/5125408.html