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

LeetCode Happy Number

2015-07-23 06:38 441 查看
原题链接在这里:https://leetcode.com/problems/happy-number/

思路就是用HashSet 存储过往的和,若是遇见了相同的和,则表示出现了无限循环,没有happy number。

Note: 1. Math.pow()的argument 和 return value 都是 double 型,返回时要注意cast。

2. ^ operator stands for XOR - exclusive OR, 不是指数相乘,今后要注意。

3. 遍历一个数字的每一位就用下面的代码:

while(n!=0){
int digit = n%10;
n = n/10;
}


AC Java:

public class Solution {
public boolean isHappy(int n) {
HashSet<Integer> hs = new HashSet<Integer>();

while(!hs.contains(n)){
if(n == 1){
return true;
}
hs.add(n);

int sum = 0;
while(n != 0){
int digit = n%10;
n = n/10;
sum += (int)Math.pow(digit,2);
}
n = sum;
}
return false;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: