LeetCode Top Interview Questions 202. Happy Number (Java版; Easy)

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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值