Leetcode202 快乐数 佛洛依德循环

  JAVA:

    public final boolean isHappy(int n) {
        int next = next(n);
        while (n != 1 && n != next) {
            n = next(n);
            next = next(next(next));
        }
        return n == 1;
    }

    private final int next(int n) {
        int re = 0;
        while (n > 0) {
            int curr = n % 10;
            n /= 10;
            re += curr * curr;
        }
        return re;
    }

 

  JS:

/**
 * @param {number} n
 * @return {boolean}
 */
var isHappy = function (n) {
    let ne = next(n);
    while (n != 1 && n != ne) {
        n = next(n);
        ne = next(next(ne));
    }
    return n == 1;
};

var next = function (n) {
    let re = 0;
    while (n > 0) {
        let curr = n % 10;
        n = Math.floor(n / 10);
        re += curr * curr;
    }
    return re;
}

 

posted @ 2020-08-12 00:30  牛有肉  阅读(187)  评论(0编辑  收藏  举报