题目原文:
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
题目大意:
判断一个数是不是“快乐的”。
快乐数的定义是:把一个正整数每个数位上的数求平方和,得到的数再求平方和……若能够得到1则为快乐数。
题目分析:
根据百度百科 任何不快乐数都会陷入4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4 的死循环。因此可以设计算法:不断求当前数的平方和,若出现上述数之一则返回false,若得到1则返回true。
源码:(language:java)
public class Solution {
public boolean isHappy(int num) {
while(true) {
if(num==1)
return true;
else if(num==4||num==16||num==37||num==58||num==89||num==145||num==42||num==20)
return false;
else {
int newnum=0;
while(num!=0) {
newnum=newnum+(num%10)*(num%10);
num=num/10;
}
num=newnum;
}
}
}
}
成绩:
2ms,beats 85.98%,众数6ms,25.67%
Cmershen的碎碎念:
Trivial的方法是,使用一个hashset记录迭代过程中出现的数字,如果出现重复的则不是快乐数。但本算法中利用了重复数字的规律可以减少迭代次数和在hashset中的比较开销,在此第二次感叹数学的强大。