LeetCode 202. 快乐数(快慢指针)

2020-07-13 15:08:36 浏览数 (1)

1. 题目

2. 解题

  • 一个数经过若干次各位数平方和后,会等于它自己
  • 使用类似环形链表的快慢指针法,最终快慢指针相遇,若不为1则是不快乐数
代码语言:javascript复制
class Solution {
public:
    int bitSquareSum(int n) {
        int sum = 0, bit;
        while(n > 0)
        {
            bit = n % 10;
            sum  = bit * bit;
            n = n / 10;
        }
        return sum;
    }
    
    bool isHappy(int n) {
        int slow = n, fast = n;
        do
        {
            slow = bitSquareSum(slow);
            fast = bitSquareSum(fast);
            fast = bitSquareSum(fast);
        }
        while(slow != fast);
        return slow == 1;
    }
};

0 人点赞