題目連結
題意:
給定一個數字
循環的計算該數字每個位數的平方之和
若最後結果為1,該數字為Happy Number
若否,則為Unhappy number
例如: 7
7^2 = 49
4^2 + 9^2 = 97
9^2 + 7^2 = 130
1^2 + 3^2 + 0^2 = 10
1^2 + 0^2 = 1
7為 Happy number
解法:
用一個Set存出現過的值
照上面的作法運算
每次結果判斷是否存在set
若否就繼續做到結果
當結果為1 ,輸出Happy number
若出現過,表示後續會一直重複
找不到最後為1的情況
輸出Unhappy Number
程式(Java):
題意:
給定一個數字
循環的計算該數字每個位數的平方之和
若最後結果為1,該數字為Happy Number
若否,則為Unhappy number
例如: 7
7^2 = 49
4^2 + 9^2 = 97
9^2 + 7^2 = 130
1^2 + 3^2 + 0^2 = 10
1^2 + 0^2 = 1
7為 Happy number
解法:
用一個Set存出現過的值
照上面的作法運算
每次結果判斷是否存在set
若否就繼續做到結果
當結果為1 ,輸出Happy number
若出現過,表示後續會一直重複
找不到最後為1的情況
輸出Unhappy Number
程式(Java):
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
public class Main { | |
public static void main(String args[]) { | |
Scanner sc = new Scanner(System.in); | |
int t = Integer.parseInt(sc.nextLine()); | |
for (int i = 1; i <= t; i++) { | |
boolean happy = true; | |
Set<Integer> set = new HashSet<Integer>(); | |
int N = Integer.parseInt(sc.nextLine()); | |
set.add(N); | |
int sum = N; | |
while (sum != 1) { | |
int N1 = sum; | |
sum = 0; | |
while ( N1 > 0 ){ | |
sum += (N1 % 10) * (N1 % 10); | |
N1 /= 10; | |
} | |
if (set.contains(sum)) { | |
happy = false; | |
break; | |
} | |
set.add(sum); | |
} | |
if (happy) | |
System.out.println("Case #" + i + ": " + N + " is a Happy number."); | |
else | |
System.out.println("Case #" + i + ": " + N + " is an Unhappy number."); | |
} | |
} | |
} |
留言
張貼留言