5月26日刷快乐数一题扩展——丑数、各位相加

80 阅读1分钟

258. 各位相加 - 力扣(Leetcode)

循环法

class Solution {
public:
    int addDigits(int num) {
        int res = num;
        if(res<10){
            return res;
        }
        while(res>=10){
            res = 0;
            while(num){
                res += num%10;
                num = num/10;
            }
            num = res;
            cout<<"res:"<<res<<endl;
        }
        return res;
    }
};

263. 丑数 - 力扣(Leetcode)

一个数能被 2,3,5分解的数则为丑数,得到了这个思路我们很简单想到 就只要除2,3,5中的任意一个就行了,注意我们不是乱除,我们要看这个数是否 能被2,3,5 “整除”,注意是整除!!!当一个数是丑数的时候我们经过以上步骤 则最后会得到 1, 不难理解为什么1也是丑数的原因(不需要做额外的判断了)。如果 不能被2,3,5整除我们得到的是别的质数而不会是1。举个例子14,14可以被2整除 然后得到 7。然后7不能被 2,3,5整除所以我们退出循环返回false。

class Solution {
public:
    bool isUgly(int n) {
        while(n)
        {
            if(n%2 == 0) n /= 2;
            else if(n%3 == 0) n /= 3;
            else if(n%5 == 0) n /= 5;
            else break;
        }
        return n == 1;
    }
};