Question
Formatted question description: https://leetcode.ca/all/202.html
202 Happy Number
Write an algorithm to determine if a number is "happy".
A happy number is a number defined by the following process:
Starting with any positive integer,
replace the number by the sum of the squares of its digits,
and repeat the process until the number equals 1 (where it will stay),
or it loops endlessly in a cycle which does not include 1.
Those numbers for which this process ends in 1 are happy numbers.
Example: 19 is a happy number
1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2 = 1
Algorithm
The example 19 given in the title is a happy number, so let’s look at a situation that is not a happy number. For example, the number 11
has the following calculation process:
1^2 + 1^2 = 2 2^2 = 4 4^2 = 16 1^2 + 6^2 = 37 3^2 + 7^2 = 58 5^2 + 8^2 = 89 8^2 + 9^2 = 145 1^2 + 4^2 + 5^2 = 42 4^2 + 2^2 = 20 2^2 + 0^2 = 4
At the end of the calculation, the number 4 appears again, then the following numbers will repeat the previous order. This cycle does not contain 1, then the number 11 is not a happy number. After discovering the pattern, we can consider how to use code it.
Use HashSet to record all the numbers that have appeared, and then every time a new number appears, look for it in HashSet to see if it exists,
- if it does not exist, add it to the table,
- if it exists, jump out of the loop, and determine whether the number is 1,
- if it is 1. Return true,
- return false if not 1
Code
Java
class Solution {
public boolean isHappy(int n) {
HashSet<Integer> set = new HashSet<Integer>();
while (!set.contains(n)) {
set.add(n);
n = getSum(n);
if (n == 1) {
return true;
}
}
return false;
}
public int getSum(int current) {
int sum = 0;
while (current > 0) {
sum += Math.pow(current % 10, 2);
current /= 10;
}
return sum;
}
}
class Solution_iteration {
public boolean isHappy(int n) {
HashSet<Integer> st = new HashSet<Integer>();
while (n != 1) {
int sum = 0;
while (n > 0) {
sum += (n % 10) * (n % 10);
n /= 10;
}
n = sum;
if (st.contains(n)) {
break;
}
st.add(n);
}
return n == 1;
}
}
// if find 4 then unhappy
class Solution_math {
public boolean isHappy(int n) {
while (n != 1 && n != 4) {
int sum = 0;
while (n > 0) {
sum += (n % 10) * (n % 10);
n /= 10;
}
n = sum;
}
return n == 1;
}
}
}