码迷,mamicode.com
首页 > 其他好文 > 详细

Ugly Number II

时间:2015-11-28 10:35:10      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:

一.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.

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

 

二.Ugly Number II

Write a program to find the n-th ugly number.

Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.

Note that 1 is typically treated as an ugly number.

class Solution {
public:
    int nthUglyNumber(int n) {
        int index2=0,index3=0,index5=0;
        int ugly2=0,ugly3=0,ugly5=0;
        vector<int> res(n,1);
        int index = 1;
        while(index < n){
            while(res[index2]*2 <= res[index-1]){
                index2++;
            }
            while(res[index3]*3 <= res[index-1]){
                index3++;
            }
            while(res[index5]*5 <= res[index-1]){
                index5++;
            }
            ugly2 = res[index2]*2;
            ugly3 = res[index3]*3;
            ugly5 = res[index5]*5;
            res[index++] = min(ugly2,min(ugly3,ugly5));
        }
        return res[n-1];
    }
};

 

Ugly Number II

标签:

原文地址:http://www.cnblogs.com/zengzy/p/5002255.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!