[LeetCode]202. Happy Number

来源:互联网 发布:网络贵金属 编辑:程序博客网 时间:2024/06/01 10:24

https://leetcode.com/problems/happy-number/



我的解法:

Time:O(N);Space:O(N)

public class Solution {    public boolean isHappy(int n) {        HashSet<Integer> set = new HashSet<>();        while (n != 1) {            if (set.contains(n)) {                return false;            }            set.add(n);            n = calHappy(n);        }        return true;    }    private int calHappy(int n) {        int res = 0;        while (n != 0) {            res += Math.pow(n % 10, 2);            n /= 10;        }        return res;    }}



最优解:

快慢指针,fast每次循环calHappy两次,slow计算一次,两者终将相遇,判断相遇时是否为一即可

Time:O(2N);Space:O(1)

public class Solution {    public boolean isHappy(int n) {        int slow = n;        int fast = n;        do {            slow = calHappy(slow);            fast = calHappy(calHappy(fast));        } while (slow != fast);        return slow == 1;    }    private int calHappy(int n) {        int res = 0;        while (n != 0) {            res += Math.pow(n % 10, 2);            n /= 10;        }        return res;    }}


0 0
原创粉丝点击