|
2 | 2 |
|
3 | 3 | import java.util.HashSet;
|
4 | 4 | import java.util.Set;
|
5 |
| -/**Write an algorithm to determine if a number is "happy". |
6 |
| - A happy number is a number defined by the following process: |
7 |
| - Starting with any positive integer, |
8 |
| - replace the number by the sum of the squares of its digits, |
9 |
| - and repeat the process until the number equals 1 (where it will stay), |
10 |
| - or it loops endlessly in a cycle which does not include 1. |
11 |
| - Those numbers for which this process ends in 1 are happy numbers. |
12 | 5 |
|
13 |
| - Example: 19 is a happy number |
14 |
| -
|
15 |
| - 12 + 92 = 82 |
16 |
| - 82 + 22 = 68 |
17 |
| - 62 + 82 = 100 |
18 |
| - 12 + 02 + 02 = 1*/ |
| 6 | +/** |
| 7 | + * 202. Happy Number |
| 8 | + * |
| 9 | + * Write an algorithm to determine if a number is "happy". |
| 10 | + * A happy number is a number defined by the following process: |
| 11 | + * Starting with any positive integer, |
| 12 | + * replace the number by the sum of the squares of its digits, |
| 13 | + * and repeat the process until the number equals 1 (where it will stay), |
| 14 | + * or it loops endlessly in a cycle which does not include 1. |
| 15 | + * Those numbers for which this process ends in 1 are happy numbers. |
| 16 | + * |
| 17 | + * Example: 19 is a happy number |
| 18 | + * |
| 19 | + * 12 + 92 = 82 |
| 20 | + * 82 + 22 = 68 |
| 21 | + * 62 + 82 = 100 |
| 22 | + * 12 + 02 + 02 = 1 |
| 23 | + */ |
19 | 24 | public class _202 {
|
20 |
| - |
21 |
| - public static boolean isHappy(int n) { |
22 |
| - if (n == 1) { |
23 |
| - return true; |
24 |
| - } |
25 |
| - Set<Integer> set = new HashSet(); |
26 |
| - while (n != 1) { |
27 |
| - String str = String.valueOf(n); |
28 |
| - n = 0; |
29 |
| - for (int i = 0; i < str.length(); i++) { |
30 |
| - int temp = Character.getNumericValue(str.charAt(i)); |
31 |
| - n += temp * temp; |
32 |
| - } |
| 25 | + public static class Solution1 { |
| 26 | + public boolean isHappy(int n) { |
33 | 27 | if (n == 1) {
|
34 | 28 | return true;
|
35 | 29 | }
|
36 |
| - if (!set.add(n)) { |
37 |
| - return false; |
| 30 | + Set<Integer> set = new HashSet(); |
| 31 | + while (n != 1) { |
| 32 | + String str = String.valueOf(n); |
| 33 | + n = 0; |
| 34 | + for (int i = 0; i < str.length(); i++) { |
| 35 | + int temp = Character.getNumericValue(str.charAt(i)); |
| 36 | + n += temp * temp; |
| 37 | + } |
| 38 | + if (n == 1) { |
| 39 | + return true; |
| 40 | + } |
| 41 | + if (!set.add(n)) { |
| 42 | + return false; |
| 43 | + } |
38 | 44 | }
|
| 45 | + return false; |
39 | 46 | }
|
40 |
| - return false; |
41 |
| - } |
42 |
| - |
43 |
| - |
44 |
| - public static void main(String... strings) { |
45 |
| - int n = 7; |
46 |
| - System.out.println(isHappy(n)); |
47 | 47 | }
|
48 | 48 | }
|
0 commit comments