【13_263】Ugly Number

简单题

Ugly Number

My Submissions
Total Accepted: 32635 Total Submissions: 94009 Difficulty: Easy

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.

Discuss中总有惊喜:

Java:

1 for (int i=2; i<6 && num>0; i++)
2     while (num % i == 0)
3         num /= i;
4 return num == 1;

Python:

1 for p in 2, 3, 5:
2     while num % p == 0 < num:
3         num /= p
4 return num == 1

C++:(其中&&之后的num怎么理解?)

1 for (int i=2; i<6 && num; i++)
2     while (num % i == 0)
3         num /= i;
4 return num == 1;

自己的:

C++:

 1 class Solution {
 2 public:
 3     bool isUgly(int num) {
 4         if (num <= 0)    
 5             return false;
 6         if (num == 1)
 7             return true;
 8             
 9         while (num != 1)    {
10             if (num % 2 == 0)   {
11                 num = num / 2;
12             }
13             else if (num % 3 == 0)  {
14                 num = num / 3;
15             }
16             else if (num % 5 == 0)  {
17                 num = num / 5;
18             }
19             else{
20                 return false;
21             }
22         }
23         return true;
24     }
25 };
原文地址:https://www.cnblogs.com/QingHuan/p/5056024.html