welcome to my blog
LeetCode Top Interview Questions 202. Happy Number (Java版; Easy)
题目描述
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:
Input: 19
Output: true
Explanation:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
第一次做; 使用快慢指针思想寻找循环; 例子:2, 就存在环; 细节: slow和fast的初始化; do while的使用; 在循环内单独判断fast是否为1会加快整体处理速度
class Solution {
    public boolean isHappy(int n) {
        //initialize
        int slow=n, fast=n;
        do{
            slow = core(slow);
            fast = core(fast);
            fast = core(fast);
            //加上这句就能超越100%了
            if(fast==1)
                return true;
        }while(slow!=fast);
        return slow==1;
    }
    public int core(int n){
        int res = 0;
        while(n>0){
            int digit = n%10;
            res = res + digit * digit;
            n = n/10;
        }
        return res;
    }
}第一次做; 用哈希表存储出现过的值; 两种循环终止条件: 1)如果哈希表含有某个值, 说明已经重复计算了, 退出循环; 2)如果哈希表不含有当前值, 并且当前值是1, 退出循环
class Solution {
    public boolean isHappy(int n) {
        HashSet<Integer> set = new HashSet<>();
        int cur = core(n);
        while(!set.contains(cur) && cur!=1){
            set.add(cur);
            cur = core(cur);
        }
        return cur==1;
    }
    public int core(int n){
        int res = 0;
        while(n>0){
            int cur = n%10;
            res = res + cur*cur;
            n = n/10;
        }
        return res;
    }
}LeetCode最优解, 使用快慢指针思想找循环; 弗洛伊德环检测算法
I see the majority of those posts use hashset to record values. Actually, we can simply adapt the Floyd Cycle detection algorithm. I believe that many people have seen this in the Linked List Cycle detection problem. The following is my code:
int digitSquareSum(int n) {
        int sum = 0, tmp;
        while (n) {
            tmp = n % 10;
            sum += tmp * tmp;
            n /= 10;
        }
        return sum;
    }
    
    bool isHappy(int n) {
        int slow, fast;
        slow = fast = n;
        do {
            slow = digitSquareSum(slow);
            fast = digitSquareSum(fast);
            fast = digitSquareSum(fast);
            if(fast == 1) return 1;
        } while(slow != fast);
         return 0;
}                









