[leetcode]Ugly Number

作者:luozhipeng   发表日期:2015-8-23  浏览:2,083次

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.

uglyNumber

 

题意:判断一个数是否为丑数,所谓丑数,就是那些因子只含2,3,5的数。

 

输入:整数num。

返回:true或者false。

 

思路:若当前数包含2,3,5因子,则除以改因子,直到不含2,3,5因子为止,若最后结果为1则返回true,否则返回false。

 


class Solution {
public:
    bool isUgly(int num) {
        if(num == 0)
            return false;
        int arr[3] = {2,3,5};
        for(int i = 0; i < 3; ++i){
            if(num%arr[i] == 0){
                num /= arr[i];
                --i;
            }
        }
        return num == 1? true:false;
    }
};

 

 

标签:

本文固定链接: http://www.luozhipeng.com/?p=476
转载请注明: luozhipeng 2015-8-23 于 罗志鹏的BLOG 发表

上一篇: :下一篇
返回顶部