202 Happy Number

Source: Internet
Author: User

202 Happy Numberquestion

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



Idea

The data of type int has 10 digits, the maximum value is , the sum of squares is, so an array of 810 size can be expressed so that the sum of squares may be computed.

Give an n value, first calculate the sum of squares of the number of this n, if this and previous occurrence (M==n also appears), then this number is not happy numbers.

Reason: If A number is happy, then all members of the its sequence are happy; If a number is unhappy, all members of the sequence are unhappy.
If a count is happy number, then the order of his numbers is reversed, and the new number is still happy. Likewise, if not, no matter how reversed, it is not happy number. If calculated and previously calculated, then this step is from that and counted, now from this and then calculate the words, and then back, is an infinite cycle.

Code
BOOL Ishappy (intN{bool hash[810] = {false}; Intm=N; while(1) {intsum= 0; while(m) {sum+= (m% 10) * (m% 10);m/= 10; }if(sum= = 1)returnTrueElse if(hash[sum] ||m==N)returnFalse hash[sum] = true;m=sum; }returnfalse;}

202 Happy Number

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.