编写一个算法来判断一个数是不是“快乐数”。
一个“快乐数”定义为:对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和,然后重复这个过程直到这个数变为 1,也可能是无限循环但始终变不到 1。如果可以变为 1,那么这个数就是快乐数。
示例:
输入: 19 输出: true 解释: 12 + 92 = 82 82 + 22 = 68 62 + 82 = 100 12 + 02 + 02 = 1
在没想到更好到方法到时候暴力也许是最好的方法,如果1000次循环都不变为1,很可能他就是死循环了
另外不要局限于一种实现,可以适当的把下面贴的代码都看一看
class Solution {
public boolean isHappy(int n) {
int time=1000;
while(time-->0){
String s = ""+n;
int ans = 0;
for(int i=0;i<s.length();i++)
ans+=Integer.parseInt(""+s.charAt(i))*Integer.parseInt(""+s.charAt(i));
if(ans==1)
return true;
n=ans;
}
return false;
}
}
做一个set的小改动,不需要到1000次循环才判断为死循
Beat 90% Fast Easy Understand Java Solution with Brief Explanation
The runtime now beats 76% but still thanks for the brief discussion and easy to understand code.
public boolean isHappy(int n) {
Set<Integer> inLoop = new HashSet<Integer>();
int squareSum,remain;
while (inLoop.add(n)) {
squareSum = 0;
while (n > 0) {
remain = n%10;
squareSum += remain*remain;
n /= 10;
}
if (squareSum == 1)
return true;
else
n = squareSum;
}
return false;
}
beat 100% java in China
class Solution {
public boolean isHappy(int num) {
if(num < 10) {
return num == 1 || num == 7;
}
int n = num;
int b = 0;
while(n > 0) {
b += (n % 10) * (n % 10);
n = n / 10;
}
return isHappy(b);
}
}
beat 95+% java
class Solution {
public boolean isHappy(int n) {
if(n == 1) return true;
boolean res = false;
HashSet<Integer> hashSet = new HashSet<>();
hashSet.add(n);
while(true){
int sum = 0;
while(n > 0){
int temp = n % 10;
n /= 10;
sum += temp * temp;
}
if(sum == 1){
res = true;
break;
}
n = sum;
if(hashSet.contains(n)) return false;
hashSet.add(n);
}
return res;
}
}
神奇数学法,java版
class Solution {
public boolean isHappy(int n) {
int slow = n, fast = n;
while (fast != 1) {
fast = digitSquareSum(fast);
fast = digitSquareSum(fast);
slow = digitSquareSum(slow);
if (slow == fast) break;
}
return fast == 1;
}
private int digitSquareSum(int n) {
int res = 0;
while (n != 0) {
res += (n % 10) * (n % 10);
n /= 10;
}
return res;
}
}
神奇数学法,C版
I see the majority of those posts use hashset to record values. Actually, we can simply adapt the Floyd Cycle detection algorithm. I believe that many people have seen this in the Linked List Cycle detection problem. The following is my code:
我看到大多数帖子都使用hashset来记录值。实际上,我们可以简单地调整Floyd Cycle检测算法。我相信许多人已经在Linked List Cycle检测问题中看到了这一点。以下是我的代码:
int digitSquareSum(int n) {
int sum = 0, tmp;
while (n) {
tmp = n % 10;
sum += tmp * tmp;
n /= 10;
}
return sum;
}
bool isHappy(int n) {
int slow, fast;
slow = fast = n;
do {
slow = digitSquareSum(slow);
fast = digitSquareSum(fast);
fast = digitSquareSum(fast);
} while(slow != fast);
if (slow == 1) return 1;
else return 0;
}