Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

263. Ugly Number

Math

Explanation

To determine if a number is ugly, we repeatedly divide it by 2, 3, and 5 as long as it is divisible by any of these numbers. If the final result is 1, then the original number is ugly. Otherwise, it is not ugly. We can implement this approach in a loop and return true if n equals 1 at the end.

  • Time complexity: O(log n) - where n is the input number
  • Space complexity: O(1)
class Solution {
    public boolean isUgly(int n) {
        if (n <= 0) return false;
        
        for (int i = 2; i < 6 && n > 0; i++) {
            while (n % i == 0) {
                n /= i;
            }
        }
        
        return n == 1;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.