leetcode-202 Happy Number

关键是当一个数不是happy number是,怎样退出循环

自己的挫方法:使用set保存之前计算的所有数

class Solution {
public:
    bool isHappy(int n) {
        if(n <= 0) return false;
        if(n == 1) return true;
        set<int> prev;
        prev.insert(n);
        while(n != 1){
            int sum = 0;
            while(n){
                int digit = n % 10;
                sum += digit * digit;
                n /= 10;
            }
            n = sum;
            if(prev.count(n)) return false;
            prev.insert(n);
            
        }
        return true;
    }
}; 

discuss里面的方法1: Using fact all numbers in [2, 6] are not happy (and all not happy numbers end on a cycle that hits this interval)

class Solution {
public:
    bool isHappy(int n) {
        if(n <= 0) return false;
        while(n > 6){
            int next = 0;
            while(n){
                int tmp = n % 10;
                next += tmp * tmp;
                n /= 10;
            }
            n = next;
        }
        return n == 1;
    }
}; 

discuss里面的方法2:Use the same way as checking cycles in a linked list

class Solution {
public:
    bool isHappy(int n) {
        if(n <= 0) return false;
        int A = nextNum(n); //A指向第一个
        int B = nextNum(A); //B指向第二个
        while(A != 1 && A != B){
            A = nextNum(A); //A每次向前走一步
            B = nextNum(B); //B每次向前走两步
            B = nextNum(B);
        }
        return A == 1;
    }
    
    int nextNum(int n){
        int next = 0;
        while(n){
            int tmp = n % 10;
            next += tmp * tmp;
            n /= 10;
        }
        return next;
    }
}; 



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值