LeetCode: Ugly Number Solution

Recursively dividing

Approach

For negative number, always false

Keep dividing 2, 3, 5, the number is ugly if the result is 1

Implementation

1var isUgly = function (n) {
2 if (n <= 0) return false
3 if (n % 2 === 0) return isUgly(n / 2)
4 if (n % 3 === 0) return isUgly(n / 3)
5 if (n % 5 === 0) return isUgly(n / 5)
6
7 return n === 1
8}

References

Original problem

Comments

Loading comments...

Tags

leetcode

recursion

math

Next Post

LeetCode: Build Array from Permutation

Straight-forward map

Previous Post

LeetCode: Flipping an Image

Bit flip made easy with coercion

HoningJS

Search Posts