[Leetcode] Ugly Number, Solution

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.

[Thoughts]
這題簡單。既然已經說了ugly number是{2,3,5}的組合乘積構成的,那麼判斷邏輯也就簡單了,對於任意一個給定的數字,拼命除這三個因子,最後能整除的就是ugly number,不然就不是。
邏輯看code
[Code]
1:  class Solution {  2:  public:  3:    bool isUgly(int num) {  4:      if (num <= 0) return false;  5:      while (num % 2 == 0) num /= 2;  6:      while (num % 3 == 0) num /= 3;  7:      while (num % 5 == 0) num /= 5;  8:      return num == 1;  9:    }  10:  };
相關文章
相關標籤/搜索