---
# System prepended metadata

title: LeetCode 263. Ugly Number
tags: [Leetcode]

---

---
title: 'LeetCode 263. Ugly Number'
disqus: hackmd
---

# LeetCode 263. Ugly Number



## Description

An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5.

Given an integer n, return true if n is an ugly number.

## Example

Input: n = 6
Output: true
Explanation: 6 = 2 × 3

Input: n = 1
Output: true
Explanation: 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5.

## Constraints

-2^31^ <= x <= 2^31^ - 1

## Answer

此題可直接除，若遇到2、3、5都不能除的情況時就表示有其他因數，故就將flag設為false，反之若都檢查完的話n會變成1，如此即return true。

```Cin=
bool isUgly(int n){
    bool flag = n > 0 ? true : false;
    while(n > 1 && flag){
        if(n%2 == 0){n /= 2;}
        else if(n%3 == 0){n /= 3;}
        else if(n%5 == 0){n /= 5;}
        else{flag = false;}
    }
    return flag;
}
```


## Link
https://leetcode.com/problems/ugly-number/
###### tags: `Leetcode` 
