<span style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; background-color: rgb(255, 255, 255);">Write an algorithm to determine if a number is "happy".</span>
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
- 12 + 92 = 82
- 82 + 22 = 68
- 62 + 82 = 100
- 12 + 02 + 02 = 1
public class Solution {
public boolean isHappy(int num) {
if (num == 0 || num == 1) {
return true;
}
Set<Integer> set = new HashSet<Integer>();
set.add(num);
while (true) {
int sum = 0;
while(num != 0){
int temp = num % 10;
sum += temp * temp;
num = num / 10;
}
if(sum == 1){
return true;
}
if (!set.add(sum)) {
return false;
}
num = sum;
}
}
}
法2:(Runtime: 9 ms)
public class Solution {
public boolean isHappy(int num) {
if (num == 0) {
return true;
}
Set<Integer> set = new HashSet<Integer>();
set.add(num);
String s = num + "";
while (Integer.parseInt(s) != 1) {
int sum = 0;
for (int i = 0; i < s.length(); i++) {
int temp = Integer.parseInt(s.charAt(i) + "");
sum += temp * temp;
}
if(!set.add(sum)){
return false;
}
s = sum + "";
}
return true;
}
}
刚开始构思时,迟迟想不到用什么办法来中断计算死循环,在网上搜索了一些资料以后,发现可以用HashSet来解决死循环问题,因为Set是不重复集合,只要发现往其中添加的数是已存在的,即可判断循环计算回到死循环节点,此时即可跳出循环。