LeetCode No.202 Happy Number | #Hashset #module #math

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容