Ugly Number

NO IMAGE
1 Star2 Stars3 Stars4 Stars5 Stars 給文章打分!
Loading...

題目

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.

思路

沒什麼好說的,就是做題之前百度了一下下什麼是“prime factors”。

程式碼

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

總結

這道題本身不難,但讓我“Time Limit Exceeded”好幾次,我以為是程式碼複雜度太高,還改進了好幾個版本,最後發現是沒有對 num <= 0 進行處理。

相關文章

程式語言 最新文章