202. 快乐数

class Solution {
    public boolean isHappy(int n) {
        Set<Integer> set=new HashSet<Integer>();
        int temp=n;
        set.add(temp);
        while(true)
        {
            temp=sum(temp);
            if(temp==1)
                return true;
            if(set.contains(temp))
                return false;
             set.add(temp);
        }
    }
    //求出这个n的各个位置数字的平方和,返回这个数
    public int sum(int n)
    {
        int sum=0;
        int y=0;    //余数10
        while(n!=0)
        {
            y=n%10;
            n=n/10;
            sum+=y*y;
        }
        return sum;
    }
}

posted @ 2019-08-07 09:03  小路不会迷路  阅读(151)  评论(0编辑  收藏  举报