當前位置:首頁 > IT技術(shù) > 其他 > 正文

leetcode202:快樂數(shù)
2022-09-06 22:56:08

package com.mxnet;

import java.util.HashSet;

public class Solution202 {

    public static void main(String[] args) {

    }

    /**
     * 編寫一個算法來判斷一個數(shù) n 是不是快樂數(shù)。
     *
     * 「快樂數(shù)」?定義為:
     * 對于一個正整數(shù),每一次將該數(shù)替換為它每個位置上的數(shù)字的平方和。
     * 然后重復(fù)這個過程直到這個數(shù)變?yōu)?1,也可能是 無限循環(huán) 但始終變不到 1。
     * 如果這個過程 結(jié)果為?1,那么這個數(shù)就是快樂數(shù)。
     * 如果 n 是 快樂數(shù) 就返回 true ;不是,則返回 false 。
     * @param n
     * @return
     * 思路:
     * 1. 使用hash結(jié)構(gòu)判斷在生成下一個數(shù)的時候是否出現(xiàn)循環(huán)
     * 2. 首先使用一個函數(shù)計算改數(shù)的每個位置的平方和
     * 3. 在循環(huán)生成下一個數(shù)的時候判斷是否出現(xiàn)循環(huán)
     * 4. 若出現(xiàn) 則停止,并判斷是否滿足快樂數(shù)定義
     * 5. 若未出現(xiàn),則一直循環(huán)生成生成
     * 6. 循環(huán)結(jié)束時判斷是否滿足條件
     */
    public boolean isHappy(int n) {
        HashSet<Integer> integers = new HashSet<>();
        while (n != 1 && !integers.contains(n)){
            integers.add(n);
            n = getNext(n);
        }
        return n == 1;
    }

    /**
     * 給定一個數(shù)字n 計算對各位數(shù)求平方和的值
     * @param n
     * @return
     */
    public int getNext(int n){
        int total = 0;
        while (n > 0){
            int d = n % 10;
            total += d * d;
            n = n / 10;
        }
        return total;
    }
}

本文摘自 :https://www.cnblogs.com/

開通會員,享受整站包年服務(wù)立即開通 >