XX数类型总结

一、常见的XX数类型

二、题目集合

263. 丑数

编写一个程序判断给定的数是否为丑数。丑数就是只包含质因数 2, 3, 5 的正整数

按照定义用循环判断即可。

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

264. 丑数 II

编写一个程序,找出第 n 个丑数。丑数就是只包含质因数 2, 3, 5 的正整数

按照定义,丑数只能由丑数产生,产生方式为某一个丑数*2或3或5,且取最小值。因此可以维护一个有序的丑数序列,下一个丑数从其中一个丑数产生。为了优化,以乘2为例,可以保存下一个比当前丑数*2要大的下标。

class Solution {
public:
    int nthUglyNumber(int n) {
        vector<int> vec{1};
        int ith2 = 0, ith3 = 0, ith5 = 0;
        while(--n > 0)
        {
            int val = min(vec[ith2]*2, min(vec[ith3]*3, vec[ith5]*5));
            vec.push_back(val);
            while(vec[ith2]*2 <= val) ith2++;
            while(vec[ith3]*3 <= val) ith3++;
            while(vec[ith5]*5 <= val) ith5++;
        }
        return vec.back();
    }
};

507. 完美数

对于一个 正整数,如果它和除了它自身以外的所有正因子之和相等,我们称它为“完美数”。
给定一个 正整数 n, 如果他是完美数,返回 True,否则返回 False

这题只是循环到n是不行的,必须优化到sqrt(n)。

class Solution {
public:
    bool checkPerfectNumber(int num) 
    {
        if(num <= 1)
            return false;
        int curSum = 1;
        int n = sqrt(num);
        for(int i = 2; i <= n; i++)
            if(num%i == 0)
            {
                curSum += i;
                curSum += num / i;
            }
        return curSum == num;
    }
};

猜你喜欢

转载自blog.csdn.net/hlk09/article/details/81806149
xx