美文网首页
202. 快乐数

202. 快乐数

作者: Andysys | 来源:发表于2019-12-30 22:25 被阅读0次
        // 快慢指针
        public boolean isHappy(int n) {
            if (n == 1) {
                return true;
            }
            int slow = n, fast = n;
            do {
                slow = bitSquareSum(slow);
                fast = bitSquareSum(fast);
                fast = bitSquareSum(fast);
            } while (slow != fast);
    
            return slow == 1;
        }
    
        private int bitSquareSum(int n) {
            int sum = 0;
            while (n > 0) {
                sum += Math.pow(n % 10, 2);
                n = n / 10;
            }
            return sum;
        }
    
    
        // 集合
        public boolean isHappy2(int n) {
            Set<Integer> set = new HashSet<>();
            int m = 0;
            while (true) {
                while (n != 0) {
                    m += Math.pow(n % 10, 2);
                    n = n / 10;
                }
                if (m == 1) {
                    return true;
                }
                if (set.contains(m)) {
                    return false;
                } else {
                    set.add(m);
                    n = m;
                    m = 0;
                }
            }
        }
    

    相关文章

      网友评论

          本文标题:202. 快乐数

          本文链接:https://www.haomeiwen.com/subject/dnbeoctx.html