Leetcode--happy number

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

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

This topic is mainly to check whether an integer is happy number. One benefit is that the input must be a positive integer, regardless of the multiple input modes. Main ideas:

1. First of all, the number of input decomposition, split it into a, ten, hundred, thousands of separate, to facilitate the next step to calculate the sum of squares;

2. End Condition: If the value is happy number, then the termination condition is sum of 1 in a loop, if the value is not happy number, then the termination condition is a cycle, whether the sum obtained by this loop has been obtained in the previous loop, if it is obtained, then it must not be happy Number.

The code is as follows:

 Public Staticarraylist<integer> L =NewArraylist<integer>();  Public Static voidPartintN) {        if(n>=10) part (n/10); L.add (n%10); }             Public Static BooleanIshappy (intN) {ArrayList<Integer> h =NewArraylist<integer>();        H.add (n); intsum = 0; intm =N;  while(Sum!=1 &&!)h.contains (sum))            {h.add (sum); Sum= 0;            L.clear ();            Part (n);  for(inti=0; I<l.size (); i++) {sum= sum + l.get (i) *L.get (i); } N=sum; }        if(Sum = = 1)            return true; Else            return false; }

Leetcode--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.