202. Happy Number

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.
Example: 
Input: 19
Output: true
Explanation: 
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1

The idea is to use one hash set to record sum of every digit square of every number occurred. Once the current sum cannot be added to set, return false; once the current sum equals 1, return true;



class Solution {
    public boolean isHappy(int n) {
        // for me the difficult part is, for integer 235, how to get 5, 3, 2 
        // so the trick is to get these single digit numbers from the very end , 
        // 235 % 10 = 5 , remain = 235 / 10 = 23  
        // 23 % 10 = 3 , remain = 23 / 10 = 2 
        // 2 % 10 = 2 . remain = 2 / 10 = 0 
        Set<Integer> set = new HashSet<>();
        int sum;
        int digit;
        while(set.add(n)){ // why add n first ? one cycle, if there is another 19 , then it should return false as well 
            sum = 0;
            while(n > 0){
                digit = n % 10;
                sum += digit * digit;
                n = n / 10; // n /= 10;
            }
            if(sum == 1){
                return true;
            }else{
                n = sum;
            }
        }
        return false;
    }
}

 

posted on 2018-11-08 02:23  猪猪&#128055;  阅读(124)  评论(0)    收藏  举报

导航