其他分享
首页 > 其他分享> > letecode [263] - Ugly Number

letecode [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.

Example 1:

Input: 6
Output: true
Explanation: 6 = 2 × 3

Example 2:

Input: 8
Output: true
Explanation: 8 = 2 × 2 × 2

Example 3:

Input: 14
Output: false 
Explanation: 14 is not ugly since it includes another prime factor 7.

题目大意

  判断一个整数是不是丑数。丑数只含有因子2,3,5.

理  解:

  若num不等于1,则循环除以2或3或5三个因子,至num等于1.若num含有这三个因子外的因子则返回false.

代 码 C++:

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

运行结果:

  执行用时 :8 ms, 在所有C++提交中击败了82.63%的用户

  内存消耗 :8.1 MB, 在所有C++提交中击败了18.02%的用户

标签:false,num%,return,Explanation,Number,263,Ugly,num,Input
来源: https://www.cnblogs.com/lpomeloz/p/11024991.html