快乐数
leetcode202
用 while(true) 和 if(fast == 1 || getNext(fast) == 1) 处理 “100” 因为处理的是数字可省去fast == 1的判断条件
class Solution {
public int getNext(int n){
int total = 0;
while(n > 0){
int d = n % 10;
n = n / 10;
total += d * d;
}
return total;
}
public boolean isHappy(int n) {
int slow = n;
int fast = n;
while(true){
if(getNext(fast) == 1)
return true;
slow = getNext(slow);
fast = getNext(getNext(fast));
if(fast == slow)
return false;
}
}
}
class Solution {
public int getNext(int n){
int total = 0;
while(n > 0){
int d = n % 10;
n = n / 10;
total += d * d;
}
return total;
}
public boolean isHappy(int n) {
int slow = n;
int fast = n;
while(fast != 1 && getNext(fast) != 1){ //&& getNext(fast) != 1 处理类似“100”
slow = getNext(slow);
fast = getNext(getNext(fast));
if(fast == slow){
return false;
}
}
return true;
/*
int slow = n;
int fast = get(n); //fast = n while一直为真
while(slow != fast){ //加上 && fast == 1 可让slow少走几步
slow = getNext(slow);
fast = getNext(getNext(fast));
}
return fast == 1;
*/
}
}