Leetcode 202. Happy number Determines whether a count is "Happy numbers"----------Java

Source: Internet
Author: User
Tags set set

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 and replace the number by the Sum of the squares of its digits, and repeat the process until the number equals 1 (where it would stay), or it loops Endl essly in a cycle which does not include 1. Those numbers for which this process ends in 1 is happy numbers.

Example:19 is a happy number

    • 12 + 92 = 82
    • 82 + 22 = 68
    • 62 + 82 = 100
    • 12 + 02 + 02 = 1

According to the above rules, if we can satisfy the above rules, then it is a happy number.

Use a set to record that there has been a count, to avoid a dead loop

 Public classSolution { Public BooleanIshappy (intN) {Set<Integer> set =NewHashSet (); returnishappynum (n, set); }         Public BooleanIshappynum (intN, set Set) {        if(Set.contains (n)) {return false;        } set.add (n); intnum = 0;  while(n! = 0) {num+ = (n%) * (n% 10); N/= 10; }        if(num = = 1){            return true; } Else {            returnishappynum (num, set); }    }}

2, the use of O (1) space complexity. Very ingenious, if there will be a cycle of the situation, then X and Y will meet, will certainly jump out of the loop.

 Public classSolution { Public BooleanIshappy (intN) {intx =N; inty =N;  while(x>1) {x=cal (x); if(x==1)return true ; Y=Cal (Cal (y)); if(y==1)return true ; if(x==y)return false; }        return true ; }     Public intCalintN) {        intx =N; ints = 0;  while(x>0) {s= S+ (x%10) * (x%10); X= X/10; }        returns; }}

Leetcode 202. Happy number Determines whether a count is "Happy numbers"----------Java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.