美文网首页
LeetCode No.202 Happy Number | #

LeetCode No.202 Happy Number | #

作者: wxqyppqm | 来源:发表于2016-11-03 15:17 被阅读0次

    Q:

    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: **19 is a happy number
    1² + 9² = 82
    8² + 2² = 68
    6² + 8² = 100
    1² + 0² + 0² = 1

    A:

    【trigger 1】当算出值为1,停止loop。

    public class Solution {
        public boolean isHappy(int n) {
            HashSet<Integer> set = new HashSet<Integer>();
            set.add(n);
    
            while (n != 1) {
                int result = 0;
    
                while (n != 0) {
                    result += Math.pow(n % 10, 2);    //计算
                    n /= 10;
                }
    
                if (set.contains(result)) {   
                    return false;
                }//collision occur, will leads to infinite loop
    
                set.add(result);   //add in set
                n = result; //keep going iteration
            }
            return true;
        }
    }
    

    【trigger 2】当发现无法add进set,意味着infinite loop要发生了,停止loop。

    The reason why duplicate value can't be added into a hash-set: In hash set and hash map, Java first use object's hashCode() function to compute the "slot" for the key. If two keys have the same hash code (this is called hash collision and it's actually very rare to happen), they will be compared by using the second key's equals() method, if return true, the two keys are exactly the same, the key will not be added(in set) or its value will be overwritten(in map); if return false, Java will create a linear chain in the slot to store both of them. (credit@mo10)

    public class Solution {
        public boolean isHappy(int n) {
            HashSet<Integer> set = new HashSet<Integer>();
    
            while (set.add(n)) {
                int result = 0;
    
                while (n > 0) {
                    result += Math.pow(n % 10, 2);    //计算
                    n /= 10;
                }
                if (result == 1) {   
                    return true;
                }
                n = result; //keep going iteration
            }
    
            return false;
        }
    }
    

    test case: 18
    1² + 8² = 65
    6² + 5² = 61
    6² + 1² = 37 <-------
    3² + 7² = 58
    5² + 8² = 89
    8² + 9² = 145
    1² + 4² + 5² = 42
    4² + 2² = 20
    2² + 0² = 4
    4² = 16
    1² + 6² = 37 <------- collision

    相关文章

      网友评论

          本文标题:LeetCode No.202 Happy Number | #

          本文链接:https://www.haomeiwen.com/subject/hqwbuttx.html