202 快乐数

 

 解法:用set进行判断是否已经迭代过一轮

class Solution {
    public boolean isHappy(int n) {
        Set<Integer> seen = new HashSet<Integer>();
        while (n != 1 && !seen.contains(n)) {
            seen.add(n);
            n = getNext(n);
        }
        return n == 1;
    }
    
    private int getNext(int n) {
        int sum = 0;
        while (n > 0) {
            int d = n % 10;
            n = n / 10;
            sum += d * d;
        }
        return sum;
    }
}

 

posted on 2022-11-10 14:35  HHHuskie  阅读(17)  评论(0编辑  收藏  举报

导航