【Lintcode】488。ハッピーナンバー

タイトルアドレス:

https://www.lintcode.com/problem/happy-number/description

正の整数を与える 、その数字の2乗の合計を求めて新しい数値を取得し、この新しい数値に対して同じ操作を続けます。最終的に得た場合 1 1 はtrueを返し、それ以外の場合はfalseを返します。

方法1:ハッシュテーブルを使用して計算された数を記録し、重複がある場合はfalseを返します。中途半端に 1 1 はtrueを返します。コードは次のとおりです。

import java.util.HashSet;
import java.util.Set;

public class Solution {
    /**
     * @param n: An integer
     * @return: true if this is a happy number or false
     */
    public boolean isHappy(int n) {
        // write your code here
        Set<Integer> set = new HashSet<>();
        set.add(n);
        int i = 0;
        while ((i = sum(n)) != 1) {
            if (!set.add(i)) {
                return false;
            }
            n = i;
        }
        
        return true;
    }
    
    private int sum(int n) {
        int res = 0;
        while (n > 0) {
            int i = n % 10;
            res += i * i;
            n /= 10;
        }
        
        return res;
    }
}

方法2:リンクされたリストを使用して、リング、高速および低速のポインターを見つけます。

public class Solution {
    public boolean isHappy(int n) {
        // write your code here
        int slow = n, fast = n;
        do {
            slow = sum(slow);
            fast = sum(sum(fast));
            if (fast == 1) {
                return true;
            }
        } while (slow != fast);
        
        return false;
    }
    
    private int sum(int n) {
        int res = 0;
        while (n > 0) {
            int i = n % 10;
            res += i * i;
            n /= 10;
        }
        
        return res;
    }
}
公開された388元の記事 ウォンの賞賛0 ビュー10000 +

おすすめ

転載: blog.csdn.net/qq_46105170/article/details/105355684
おすすめ