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

Jul 26, 2022

Straight-forward map

Previous Post

LeetCode: Flipping an Image

Jul 19, 2022

Bit flip made easy with coercion

HoningJS

Search Posts