Problem 202. Happiness number Write an algorithm to determine whether a number n is a happy number.
The happy number is defined as replacing a positive integer each time with the sum of the squares of the numbers in each of its positions, and then repeating the process until the number becomes 1, possibly indefinitely. If you can change it to 1, then that number is happiness.
Return True if n is the happy number; If not, return False.
“Example:”
Input: 19 Output: true Description: 12 + 92 = 82 82 + 22 = 68 62 + 82 = 100 12 + 02 + 02 = 1
This problem looks like a math problem, but it’s not!
If the sum is repeated over and over again, it is important to solve the problem.
As: Here’s what you should know about hash tables! “Hashing comes into play when we need to quickly determine whether an element is present in a set.”
If sum is repeated, return false. If sum is repeated, return false until sum is 1.
To determine if sum is repeated, use unordered_set.
“Another difficulty is the summation process, which can also be difficult if you are not familiar with the odd digits.”
An infinite loop, which contains this sum, is a good way to use set; And then this code is natural, there’s no algorithm, it’s just a getSum method that gives you a bunch of judgments based on conditions.
import java.util.*;
class Solution {
int getSum(int n){
int sum=0;
while(n > 0) {/ / the judgment condition here is n > 0 sum = sum + (n % 10) * (n % 10); // Start at the end and get the square of each digit, keep adding n = n/10; // Change sum as well as n}return sum;
}
public boolean isHappy(int n) {
Set verdictSet=new HashSet();
while(true){ int sum = getSum(n); // After getting the result, there are only three cases to judgeif(sum==1){
return true;
}else if(verdictSet.contains(sum)){
return false;
}else{ verdictSet.add(sum); } // sum =sum; }}}Copy the code
Set and map can be used interchangeably as follows
import java.util.*;
class Solution {
public int getSum(int n){
int sum = 0;
while(n > 0){
sum = sum + (n%10) * (n%10);
n = n / 10;
}
return sum;
}
public boolean isHappy(int n) {
Map verdictMap = new HashMap();
while(true){
int sum = getSum(n);
if(sum == 1){
return true;
}
else if (verdictMap.containsKey(sum)){
return false;
}else{
verdictMap.put(sum,"xx"); } n = sum; }}}Copy the code