"Leetcode" Happy number (Easy)

Source: Internet
Author: User

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

Ideas:

This topic is very interesting, certainly can not really through the infinite cycle to judge. I looked at the numbers that were not happy, and the numbers that had already appeared before the operation, that is, circled in a set of numbers. Therefore, record the number of occurrences and decide whether to repeat.

If the repetition is not happy, get 1 happy.

BOOLIshappy (intN) {unordered_set<int>record;  while(1)        {            intsum =0;  while(N >0) {sum+ = (n%Ten) * (n%Ten); N/=Ten; }            if(Sum = =1)                return true; if(Record.find (sum) = = Record.end ())//The current number has not appeared.{record.insert (sum); N=sum; }            Else                return false; }    }

Also useful O (1) space, like a chain list to find a circle, with the idea of a fast and slow pointer.

 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; }}

Also useful in mathematics, all the numbers that are not happy will get 4. Why

BOOLIshappy (intN) {if(N <=0)return false; intMagic =4;  while(1) {        if(n = =1)return true; if(n = = Magic)return false; intt =0;  while(n) {T+ = (n%Ten) * (n%Ten); N/=Ten; } N=T; }}

"Leetcode" Happy number (Easy)

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.