[Leetcode] Happy number

Source: Internet
Author: User

1. First question

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.

2.happy number

(First of all, the characteristics of happy number, the problem is not used for the time being.) )

If a number is happpy, then all of the squared and composed sequences that are calculated during validation are happy number. For example, 19 is happy number, and (82,68,100) is also. If a number is not, the same ... Neither the square nor the sequence. And happy number each is re-assembled, the new numbers are happy. (e.g. 91). Insert 0 at any location in Happy number, and the new numbers are happy.

See Http://en.wikipedia.org/wiki/Happy_number for a detailed introduction to happy number

3. Analysis

3.1 End condition

If a number, the sum of the squares of each digit is equal to 1, the number is happy, and if there is no sum equal to 1 in the process of the calculation, and there is a loop, it is not happy.

3.2 The values in the squared and sequence,hashset<> that can be computed with HashSet records cannot be duplicated and have no order, and the capacity will grow automatically on demand.

4. Code

public boolean ishappy (int n) {

if (n<=0) return false;
Hashset<integer> showednum=new hashset<> ();

while (N<=integer.max_value) {
if (Showednum.contains (n)) return false;
else Showednum.add (n);
N=digitsquare (n);
if (n==1) {
SYSTEM.OUT.PRINTLN ("yes");
return true;
}
}
return false;
}
public int Digitsquare (int n) {
int s=0,temp;
while (n!=0) {
temp=n%10;
S+=temp*temp;
N=N/10;
}
return s;
}

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