@@ -0,0 +1,1865 @@
+import java.util.HashSet;%0Aimport java.util.Set;%0A%0A/**%0A * Write an algorithm to determine if a number is %22happy%22.%0A *%0A * A happy number is a number defined by the following process: Starting with any positive integer, replace the number%0A * by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it%0A * loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy%0A * numbers.%0A *%0A * Example:%0A * 19 is a happy number%0A * 1%5E2 + 9%5E2 = 82%0A * 8%5E2 + 2%5E2 = 68%0A * 6%5E2 + 8%5E2 = 100%0A * 1%5E2 + 0%5E2 + 0%5E2 = 1%0A *%0A * Tags: Hash Table Math%0A * Similar Problems: (E) Add Digits (E) Ugly Number%0A */%0Apublic class HappyNumber %7B%0A%0A    public static void main(String%5B%5D args) %7B%0A        HappyNumber hn = new HappyNumber();%0A        for (int i = 10; i %3C 20; i++) %7B%0A            System.out.println(i + %22: %22 + hn.isHappy(i));%0A            System.out.println(i + %22: %22 + hn.isHappy2(i));%0A        %7D%0A    %7D%0A%0A    /**%0A     * loop detection like linked list%0A     */%0A    public boolean isHappy(int n) %7B%0A        int slow, fast;%0A        slow = fast = n;%0A        do %7B%0A            slow = digitSquareSum(slow);%0A            fast = digitSquareSum(digitSquareSum(fast));%0A        %7D while (slow != fast);%0A        return slow == 1;%0A    %7D%0A%0A    /**%0A     * loop detection using Set, use more space%0A     */%0A    public boolean isHappy2(int n) %7B%0A        if (n %3C 1) return false;%0A%0A        int num = n;%0A        Set%3CInteger%3E results = new HashSet%3C%3E();%0A        while (!results.contains(num)) %7B%0A            results.add(num);%0A            num = digitSquareSum(num);%0A        %7D%0A        %0A        return num == 1;%0A    %7D%0A%0A    public int digitSquareSum(int n) %7B%0A        int res = 0;%0A        int digit;%0A        for (; n %3E 0; n /= 10) %7B%0A            digit = n %25 10;%0A            res += digit * digit;%0A        %7D%0A        return res;%0A    %7D%0A%7D%0A

add 202 happy number