码迷,mamicode.com
首页 > 移动开发 > 详细

Leetcode: Happy Number

时间:2015-12-15 06:22:36      阅读:215      评论:0      收藏:0      [点我收藏+]

标签:

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, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.

Example: 19 is a happy number

12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 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 *= 10 each time. This might gives rise to overflow in line 12 when cur * 10. To overcome this I have to define cur to be a long.

The best way to get each digit is to use n%10, and n /=10 each loop. Dividing will avoid unnecessary overflow.

BTW, no need to define an arraylist to store all the digits.

 1 public class Solution {
 2     public boolean isHappy(int n) {
 3         if (n <= 0) return false;
 4         if (n == 1) return true;
 5         HashSet<Integer> set = new HashSet<Integer>();
 6         while(!set.contains(n)) {
 7             set.add(n);
 8             long cur = 1;
 9             ArrayList<Integer> digits = new ArrayList<Integer>();
10             int sum = 0;
11             while (n / cur >= 1) {
12                 digits.add((int)(n % (cur*10) / cur));
13                 cur *= 10;
14             }
15             for (int digit : digits) {
16                 sum += (int)Math.pow(digit, 2);
17             }
18             n = sum;
19             if (n == 1) return true;
20         }
21         return false;
22     }
23 }

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

but it is incorrect as: sum = sum + Math.pow(digit, 2), should write as sum = sum + (int)Math.pow(digit, 2)

So better cast pow into integer before use it.

 

Second Time: Better

The best way to get each digit is to use n%10, and n /=10 each loop. 

 1 public class Solution {
 2     public boolean isHappy(int n) {
 3         if (n <= 0) return false;
 4         if (n == 1) return true;
 5         HashSet<Integer> set = new HashSet<Integer>();
 6         while(!set.contains(n)) {
 7             set.add(n);
 8             int sum = 0;
 9             while (n > 0) {
10                 sum += (int)Math.pow(n%10, 2);
11                 n /= 10;
12             }
13             n = sum;
14             if (n == 1) return true;
15         }
16         return false;
17     }
18 }

 

Leetcode: Happy Number

标签:

原文地址:http://www.cnblogs.com/EdwardLiu/p/5046973.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!