Leetcode:happy number

Source: Internet
Author: User

If a number is ' happy ' for this process ends in 1are a happynumber 1 2 + 92 = 8282 + 22 = 6862 + 82 = 10012 + 02 + 02 = 1

First Time:not good, when I-try to get-to-the-most significant bit, I-define current bit called cur, and cur *= all t Ime. This might gives rise to overflow on line when cur * 10. To overcome this I has to define cur to be a long.

The best-of-the-digit is-to-use n%10, and N-/=10 each loop. Dividing'll avoid unnecessary overflow.

BTW, no need to define a ArrayList to store all the digits.

1  Public classSolution {2      Public BooleanIshappy (intN) {3         if(n <= 0)return false;4         if(n = = 1)return true;5Hashset<integer> set =NewHashset<integer>();6          while(!set.contains (n)) {7 Set.add (n);8             LongCur = 1;9arraylist<integer> digits =NewArraylist<integer>();Ten             intsum = 0; One              while(N/cur >= 1) { ADigits.add ((int) (n% (cur*10)/cur)); -Cur *= 10; -             } the              for(intdigit:digits) { -Sum + = (int) Math.pow (digit, 2); -             } -n =sum; +             if(n = = 1)return true; -         } +         return false; A     } at}

About syntax, line + it is correct to write it as:sum + = Math.pow (digit, 2),

But it's incorrect as:sum = sum + math.pow (digit, 2), should write as Sum = sum + (int) Math.pow (digit, 2)

So better cast pow to integer before use it.

Second Time:better

The best-of-the-digit is-to-use n%10, and N-/=10 each loop.

1  Public classSolution {2      Public BooleanIshappy (intN) {3         if(n <= 0)return false;4         if(n = = 1)return true;5Hashset<integer> set =NewHashset<integer>();6          while(!set.contains (n)) {7 Set.add (n);8             intsum = 0;9              while(N > 0) {TenSum + = (int) Math.pow (N%10, 2); OneN/= 10; A             } -n =sum; -             if(n = = 1)return true; the         } -         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.