[LeetCode202]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,否则不是)

思路:同计算循环小数一样,把每次计算的结果保存到一个List<int>里,如果出现循环,则返回false即可

代码:

public class Solution {
    public bool IsHappy(int n) {
        int sum = n;
        if(n <= 0)
            return false;
        List<int> appearedNum = new List<int>();
        while(true)
        {
            if(appearedNum.Contains(sum))
                return false;
            else
                appearedNum.Add(sum);
            sum = GetNext(sum);
            if(sum == 1)
                return true;
        }
        return true;
    }
    
    public int GetNext(int num)
    {
        int sum = 0;

        while(num != 0)
        {
            sum += (int)Math.Pow(num % 10, 2);
            num /= 10;
        }
        return sum;
    }
}

 

posted @ 2015-12-19 20:52  zhangbaochong  阅读(522)  评论(0编辑  收藏  举报