llllmz

导航

202. 快乐数 C

没有意识到这是一个环。

原理就是,其区间是有限的(int型变量存在最大值pow(2,31)-1),而循环却是无限的,那么一定会发生重复的情况。

如果不重复,那么和区间有限矛盾。

int c_sum(int n){
    int sum=0;
    while(n!=0){
        int t=n%10;
        n/=10;
        sum+=pow(t,2);
    }
    return sum;
}

bool isHappy(int n) {
    int fast=c_sum(n);
    fast=c_sum(fast);
    int slow=c_sum(n);
    while(fast!=slow){
        fast=c_sum(fast);
        fast=c_sum(fast);
        slow=c_sum(slow);
    }
    if(slow==1) return true;
    return false;
}

结果:

posted on 2024-02-28 20:47  神奇的萝卜丝  阅读(14)  评论(0)    收藏  举报