自学内容网 自学内容网

力扣202.快乐数

202. 快乐数 - 力扣(LeetCode)

主要是用到了鸽巢原理,最后他们一定会重合,我们只需要判断类似,链表的成环相遇的时候是不是1就行了

class Solution {
public:

    int bitsum(int n)
    {
        int sum = 0;
        while (n)
        {
            int a = 0;
            a = n % 10;
            sum += a * a;
            n /= 10;
        }
        return sum;
    }
    bool isHappy(int n) {
        int fast = bitsum(n);
        int slow = n;
        while (fast != slow)
        {
            fast = bitsum(fast);
            fast = bitsum(fast);
            slow = bitsum(slow);
        }
        if (fast == 1)
        {
            return true;
        }
        else return false;
    }
};


原文地址:https://blog.csdn.net/gyj215500/article/details/140698160

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!