Algorithm questions daily practice---Day 76: Ugly number l

Get into the habit of writing together! This is the 11th day of my participation in the "Nuggets Daily New Plan · April Update Challenge", click to view the details of the event .

1. Problem description

**Ugly numbers** are   positive integers that only contain prime factors 2and 3 sums  .5

Give you an integer  n , please judge  n whether it is an **ugly number**. If yes, return  true ; otherwise, return  false .

Topic link: ugly number l

Second, the subject requirements

Example 1

输入: n = 6
输出: true
解释: 6 = 2 × 3
复制代码

Example 2

输入: n = 1
输出: true
解释: 1 没有质因数,因此它的全部质因数是 {2, 3, 5} 的空集。
复制代码

visit

1.贪心、模拟
2.建议用时15~35min
复制代码

3. Problem Analysis

This question is actually a simple judgment. For example, my initial idea was to see if this number can be multiplied by several 2 3 5. If it is possible, return it true, otherwise return it false.

The code I originally wrote was a bit long, but easy to understand.

Later, I found out that this method can be optimized, and the triple loop nesting is too bad.

optimization

The thought is still the same thought, but the triple cycle is divided into separate ones.

1.n是2的倍数,进入循环/2
2.n是3的倍数,进入循环/3
3.n是5的倍数,进入循环/5
复制代码

Fourth, the encoding implementation

1. Initial version

class Solution {
public:
    bool isUgly(int n) {//(●>ω<●)
        int i,j,k,a,b,c;//初始化数据
        for(i=0;pow(2,i)<=n;i++)//判断有几个2
        {
            a=pow(2,i);
            for(j=0;pow(3,j)<=n/a;j++)//判断有几个3
            {
                b=pow(3,j);
                for(k=0;pow(5,k)<=n/(a*b);k++)//判断有几个5
                {
                    c=pow(5,k);
                    if(a*b*c==n)//如果能够构成,返回true
                        return true;
                }
            }
        }
        return false;//不能构成,返回false
    }
};
复制代码

2. After optimization

class Solution {
public:
    bool isUgly(int n) {
        if(n<1) return false;//n为0,返回false
        while(n%2==0)   n=n/2;//进入2循环
        while(n%3==0)   n=n/3;//进入3循环
        while(n%5==0)   n=n/5;//进入5循环
        if(n==1)//结果是1,那么肯定能被2 3 5组成
            return true;
        else//否则不能
            return false;
    }
};
复制代码

5. Test results

1.png

2.png

The optimized execution time is significantly lower.

Guess you like

Origin juejin.im/post/7085127574804201480