intgetNext(int n){ int sum = 0; while(n > 0){ //用循环来处理正整数的每一位 int a = n % 10; sum += a * a; n /= 10; } return sum; } boolisHappy(int n){ int fast = n,slow = n; do{ slow = getNext(slow); fast = getNext(fast); fast = getNext(fast); }while(fast != slow);
return slow == 1; }
LeetCode 各位相加
一样的模板
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
intgetNext(int n){ int a; int sum = 0; while(n > 0){ a = n % 10; sum += a; n /= 10; } return sum; } intaddDigits(int n){ int fast = n,slow = n; do{ fast = getNext(fast); fast = getNext(fast); slow = getNext(slow); }while(fast != slow); return slow; }