263. Ugly Number

263. Ugly Number

Write a program to check whether a given number is an ugly number.

Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 6, 8 are ugly while 14 is not ugly since it includes another prime factor 7.

Note that 1 is typically treated as an ugly number.
Link:
https://leetcode.com/problems/ugly-number/
Analysis:
方法一:找出这个数所有的质因数,这样在数大的时候计算量还是挺大的,会超时。
方法二:直接将其2、3、5的公约数全部约分,看最后是否等于1 。若等于1,则质因数只有2、3、5啦。
Source Code(C++):

#include <iostream>
#include <vector>
using namespace std;
/***************************找出所有的质因数,这种方法超时*******************************************/
/*
class Solution {
public:
    bool isUgly(int num) {
        if (num<1){
            return false;
        }
        else if(num == 1) {
            return true;
        }
        else {
            int k=2;
            vector<int> prime_number;
            while(num!=1) {
                if (num%k==0) {
                    prime_number.push_back(k);
                    num /= k;
                }
                else {
                    k++;
                }
            }
            for(int i=0; i<prime_number.size(); i++)
            {
                if (prime_number.at(i)!=2 &&prime_number.at(i)!=3 && prime_number.at(i)!=5 ) {
                    return false;
                }
            }
            return true;
        }
    }
};
*/

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

int main() {
    Solution sol;
    cout << sol.isUgly(90);
    return 0;
}

你可能感兴趣的:(263. Ugly Number)