class Solution {
public boolean isHappy(int n) {
while(true){
int x1 = n;
int sum=0;
while(x1 > 0){
x1 = n/10;
int x2 = n%10;
sum += x2 * x2;
n = n/10;
}
n = sum;
if(n==1)return true;
if(n<10 & n!=7 ) break;
}
return false;
}
}
上面是我写的代码,我很好奇,7这个数字好奇怪呀!
求解每一位的平方和的方法:
while(n > 0){
int digit = n % 10;
sum += digit * digit;
n /= 10;
}
boolean判断的方式:
return slow == 1;
快慢指针的思想求解:(方法很好,很能体现快慢指针思想的精髓)
public class Solution {
public int squareSum(int n) {
int sum = 0;
while(n > 0){
int digit = n % 10;
sum += digit * digit;
n /= 10;
}
return sum;
}
public boolean isHappy(int n) {
int slow = n, fast = squareSum(n);
while (slow != fast){
slow = squareSum(slow);
fast = squareSum(squareSum(fast));
};
return slow == 1;
}
}
代码随想录的卡尔用的是Set集合(哈希法) 我觉得也很好
用set集合去判断某个元素是否会重复的问题
public boolean isHappy(int n) {
Set<Integer> record = new HashSet<>();
while (n != 1 && !record.contains(n)) {
record.add(n);
n = getNextNumber(n);
}
return n == 1;
}
private int getNextNumber(int n) {
int res = 0;
while (n > 0) {
int temp = n % 10;
res += temp * temp;
n = n / 10;
}
return res;
}