↓Skip to main content
  1. LeetCode/

LeetCode 263: Ugly Number

·1 min· ·
LeetCode Easy Math
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-08-23

  • Submissions: Accepted (first try)

Approach
#

n <= 0 never qualifies. Otherwise divide out 2, 3 and 5 as long as possible; if 1 remains there are no other prime factors (Number Theory).

My Solution
#

class Solution:
    def isUgly(self, n: int) -> bool:
        if n <= 0:
            return False
        for p in (2, 3, 5):
            while n % p == 0:
                n //= p
        return n == 1

Complexity
#

Time O(log n), space O(1).

Mistakes to Avoid
#

  • Rule out 0 and negatives first; 0 % p == 0 would loop forever.

Interview Explanation
#

I rule out non-positive numbers, divide out 2, 3 and 5, and check that 1 remains. Time O(log n).

Related

LeetCode 292: Nim Game
·1 min
LeetCode Easy Math Brainteaser Minimax-Algorithm Game-Theory
LeetCode 292 note: whoever faces a multiple of 4 stones loses, so the first player wins when n % 4 != 0
LeetCode 326: Power of Three
·1 min
LeetCode Easy Math Recursion
LeetCode 326 note: divide by 3 while possible and check for 1; without loops, n is a power of three exactly when it divides 3^19
LeetCode 268: Missing Number
·1 min
LeetCode Easy Array Hash-Table Math Binary-Search
LeetCode 268 note: the sum of 0..n minus the array’s sum is the missing number, which may be 0
LeetCode 342: Power of Four
·1 min
LeetCode Easy Math Bit-Manipulation Recursion
LeetCode 342 note: confirm a power of two, then that the single 1 sits at an even position: n & 0x55555555 != 0, or n % 3 == 1
LeetCode 367: Valid Perfect Square
·1 min
LeetCode Easy Math Binary-Search
LeetCode 367 note: binary search [1, num] for mid² == num without using sqrt
LeetCode 405: Convert a Number to Hexadecimal
·2 mins
LeetCode Easy Math String Bit-Manipulation
LeetCode 405 note: add 2^32 to a negative number to get its two’s complement, then take 4 bits at a time (% 16); handle 0 separately