"Leetcode" 202. Happy number

Source: Internet
Author: User

Title:

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: is a happy number

    • 1^2 + 9^2 = 82
    • 8^2 + 2^2 = 68
    • 6^2 + 8^2 = 100
    • 1^2 + 0^2 + 0^2 = 1
Tips:

The key to the problem is to determine if the calculation of happy number is in the loop. One is the sum of squares calculated for each step and inserted into the hash set, if the number already exists, indicating that it has entered the loop state, then the number is not happy.

Another method is to save the sum of squares into an array (vector). Then each traversal to find the square and whether it has ever occurred.

Although the hash set is O (1), the vector traversal is O (n), but because the number is not many, the method of traversing is also very fast.

Pure Mathematical Method:

There is a mathematical proof of the cyclic sequence of happy number, and we can judge whether there is a loop by judging the sum of squares and whether "4" is present. See this article for specific proof.

Code:

Here's how to use vector traversal:

classSolution { Public:    BOOLIshappy (intN) {vector<int>Nums; intresult;  while(true) {            if(n = =1)return true;            Nums.push_back (n); Result=0;  while(n! =0) {result+ = (n%Ten) * (n%Ten); N= N/Ten; }             for(inti =0; I < nums.size (); ++i) {if(Nums[i] = = result)return false; } N=result; }    }};

"Leetcode" 202. Happy number

Related Article

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.