W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
編寫(xiě)一個(gè)算法來(lái)判斷一個(gè)數(shù) n 是不是快樂(lè)數(shù)。
「快樂(lè)數(shù)」定義為:對(duì)于一個(gè)正整數(shù),每一次將該數(shù)替換為它每個(gè)位置上的數(shù)字的平方和,然后重復(fù)這個(gè)過(guò)程直到這個(gè)數(shù)變?yōu)?1,也可能是 無(wú)限循環(huán) 但始終變不到 1。如果 可以變?yōu)? 1,那么這個(gè)數(shù)就是快樂(lè)數(shù)。
如果 n 是快樂(lè)數(shù)就返回 True ;不是,則返回 False 。
示例:
輸入:19
輸出:true
解釋:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
class Solution {
public boolean isHappy(int n) {
Set<Integer> set = new HashSet<>();
set.add(n);
while (true){
n = create(n);
if(n == 1)
return true;
if(set.contains(n))
return false;
set.add(n);
}
}
private int create(int n) {
int sum = 0;
while (n != 0){
sum += n % 10 * (n % 10);
n /= 10;
}
return sum;
}
}
class Solution {
public boolean isHappy(int n) {
Set<Integer> happySet = new HashSet();
return judge(n, 0, happySet) == 1;
}
public int judge(int n, int happy, Set<Integer> happySet) {
while(n >= 10) {
int x = n % 10;
n = n / 10;
happy += x*x;
}
happy += n*n; //這個(gè)happy是經(jīng)過(guò)平方和后的新數(shù)
if(!happySet.add(happy)) {
return happy;
}
return happy == 1 ? happy : judge(happy, 0, happySet);
}
}
public boolean isHappy2(int n){
int slow = n, fast = create(n);
while(fast != 1){
if(fast == slow) return false; // 快指針等于慢指針,這個(gè)說(shuō)明在計(jì)算過(guò)程中循環(huán)了,數(shù)字之間構(gòu)成了環(huán)。
fast = create(create(fast));
slow = create(slow);
}
return true;
}
private int create(int n) {
int sum = 0;
while (n != 0){
sum += n % 10 * (n % 10);
n /= 10;
}
return sum;
}
python
class Solution:
def isHappy(self, n: int) -> bool:
happy_set = set()
flag = self.judge(n, 0, happy_set)
return flag == 1
def judge(self, n: int, happy: int, happy_set: set) -> int:
while(n >= 10):
x = n % 10
happy += x*x
n = n // 10
happy += n*n #這個(gè)happy是經(jīng)過(guò)平方和后新的新數(shù)
if(not(happy in happy_set)):
happy_set.add(happy)
else:
return happy
return happy if happy == 1 else self.judge(happy, 0, happy_set)
HashSet(Collection<? extends E> c) 構(gòu)造一個(gè)包含指定集合中的元素的新集合。
HashSet(int initialCapacity) 構(gòu)造一個(gè)新的空集合;
背景HashMap實(shí)例具有指定的初始容量和默認(rèn)負(fù)載因子(0.75)。
HashSet(int initialCapacity, float loadFactor) 構(gòu)造一個(gè)新的空集合; 背景HashMap實(shí)例具有指定的初始容量和指定的負(fù)載因子。
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: