LeetCode 263

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.

 

 1 /*   2ms     */
 2 
 3 public class Solution {
 4     
 5     int quyu(int a,int q){
 6         while(a%q==0){
 7             a=a/q;
 8         }return a;
 9     }
10     public boolean isUgly(int num) {
11         
12         if(num==0){
13             return false;
14         }
15         num=quyu(num,2);
16         num=quyu(num,3);
17         num=quyu(num,5);
18         
19         if(num==1){
20             return true;
21         }else{
22             return false;
23         }
24     }
25 }

 

 1 /*     5ms   */
 2 
 3 public class Solution {
 4     
 5     public boolean isUgly(int num) {
 6         
 7         if(num==0) return false;
 8         while(num%2==0) num/=2;
 9         while(num%3==0) num/=3;
10         while(num%5==0) num/=5;
11         
12         if(num==1) return true;
13         else return false;
14     }
15 }

 

 

 1 /*************************************************************************
 2     > File Name: LeetCode263.c
 3     > Author: Juntaran
 4     > Mail: JuntaranMail@gmail.com
 5     > Created Time: Wed 18 May 2016 19:45:08 PM CST
 6  ************************************************************************/
 7 
 8 /*************************************************************************
 9     
10     Ugly Number
11     
12     Write a program to check whether a given number is an ugly number.
13 
14     Ugly numbers are positive numbers whose prime factors 
15     only include 2, 3, 5. For example, 6, 8 are ugly while 14 is not ugly 
16     since it includes another prime factor 7.
17 
18     Note that 1 is typically treated as an ugly number.
19 
20  ************************************************************************/
21 
22 #include <stdio.h>
23 
24 int quyu( int num, int q )
25 {
26     while( num % q == 0 )
27     {
28         num = num / q;
29     }
30     return num;
31 }
32 
33 int isUgly(int num) 
34 {
35     if( num <= 0 )
36     {
37         return 1;
38     }
39     num = quyu( num, 2 );
40     num = quyu( num, 3 );
41     num = quyu( num, 5 );
42     
43     if( num == 1 )
44     {
45         return 1;
46     }
47     else
48     {
49         return 0;
50     }
51 }
52 
53 int main()
54 {
55     int num = 6;
56     int ret = isUgly(num);
57     printf("%d\n", ret);
58 }

 

posted @ 2016-04-24 23:16  Juntaran  阅读(185)  评论(0编辑  收藏  举报