您的位置:首页 > 移动开发

202 Happy Number

2015-08-08 16:52 281 查看
题目链接:https://leetcode.com/problems/happy-number/

题目:

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


解题思路:

- 对数字 n 的每一位平方求和为 sum。

- 若 sum 为 1,返回 true;

- 若 sum 不为1,判断 list 中是否有该键

- 没有,就添加到 list 中

- 有,则说明正在经历循环,跳出循环结束程序

注意:

无法确定是第几次对数字位数求出的和进入了循环。因而不可以假定第一次求和产生的数为loop的第一个数。也不可以假定求和产生的最大最小数为loop中的数。

一开始只想到用 HashMap 来判断是否有重复的数,其实也可以选用别的数据结构,例如 arrayList,LinkedList 等。毕竟只用判断当前求出的和是否过去已经出现过,而不必用知道它出现了几次。实际上 map 的值的部分空间被浪费了。

public class Solution {
public boolean isHappy(int n) {
if(n == 0)
return false;
if(n == 1)
return true;
ArrayList<Integer> list = new ArrayList();
boolean res = false;
while(true) {
int sum = 0;
while(n != 0) {
int p = n % 10;
n = n / 10;
sum += p * p;
}
if(sum == 1) {
res = true;
break;
}
if(list.contains(sum))
break;
list.add(sum);
n = sum;
}
return res;
}
}


400 / 400 test cases passed.
Status: Accepted
Runtime: 220 ms
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: