顿搜
飞过闲红千叶,夕岸在哪
类目归类
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.
19 is a happy number
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
private HashSet<String> set = new HashSet<String>();
public boolean isHappy(int n) {
if (n <= 0) {
return false;
}
if (n == 1) {
return true;
}
String num = String.valueOf(n);
if (set.contains(num)) {
return false;
}
set.add(num);
int sum = 0;
for (int i = 0; i < num.length(); i++) {
int tmp = num.charAt(i) - '0';
sum += tmp * tmp;
}
return isHappy(sum);
}import java.util.HashSet;
public class LeetCode0202 {
private HashSet<String> set = new HashSet<String>();
public boolean isHappy(int n) {
if (n <= 0) {
return false;
}
if (n == 1) {
return true;
}
String num = String.valueOf(n);
if (set.contains(num)) {
return false;
}
set.add(num);
int sum = 0;
for (int i = 0; i < num.length(); i++) {
int tmp = num.charAt(i) - '0';
sum += tmp * tmp;
}
return isHappy(sum);
}
public static void main(String[] args) {
LeetCode0202 leetcode = new LeetCode0202();
System.out.println(leetcode.isHappy(19));
}
}