1. Description
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.
2. Runtime Distribution
3. Submission Details
4. Example
19 is a happy number
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
5. Code
[restabs alignment="osc-tabs-right" responsive="true" icon="true" text="More" seltabcolor="#fdfdfd" seltabheadcolor="#000" tabheadcolor="blue"]
[restab title="Java" active="active"]
private HashSetset = new HashSet (); 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); }
[/restab]
[/restabs]
6.Test
[restabs alignment="osc-tabs-right" responsive="true" icon="true" text="More" seltabcolor="#fdfdfd" seltabheadcolor="#000" tabheadcolor="blue"]
[restab title="Java" active="active" ]
import java.util.HashSet;
public class LeetCode0202 {
private HashSet set = new HashSet();
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));
}
}
[/restab]
[/restabs]



Comments | NOTHING