Browser tab content: Problem List 0 Debugging... Run Submit 00:00:00 Description…
- User
Browser tab content: Problem List 0 Debugging... Run Submit 00:00:00 Description Editorial Editorial Solutions Solutions Submissions Submissions Code Note Note Testcase Testcase Test Result 263. Ugly Number Easy Topics Companies
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 1:
Input: n = 6 Output: true Explanation: 6 = 2 × 3
Example 2:
Input: n = 1 Output: true Explanation: 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5.
Example 3:
Input: n = 14 Output: false Explanation: 14 is not ugly since it includes the prime factor 7.
Constraints:
-231 <= n <= 231 - 1 Seen this question in a real interview before? 1/5 Yes No Accepted 572.3K Submissions 1.4M Acceptance Rate 42.2% Topics Math Companies 0 - 3 months Google 3 0 - 6 months Meta 2 Microsoft 2 6 months ago Amazon 8 Bloomberg 7 Adobe 5 Apple 5 Uber 4 J.P. Morgan 3 Similar Questions Happy Number Easy Count Primes Medium Ugly Number II Medium Discussion (88) Choose a type Preview Comment 💡 Discussion Rules
-
Please don't post any solutions in this discussion.
-
The problem discussion is for asking questions about the problem or for sharing tips - anything except for solutions.
-
If you'd like to share your solution for feedback and ideas, please head to the solutions tab and post it there.
Sort by:Best No comments yet. 1 2 3 4 5 6 9 Copyright ©️ 2024 LeetCode All rights reserved 3.5K 88 Java Auto 1 2 3 4 5 class Solution { public boolean isUgly(int n) { } } Saved Ln 1, Col 1 You must run your code first
Flatten 2D Vector - LeetCode
Problem List Tag 189. Rotate Array
Med.
- Reverse Bits
Easy
- Number of 1 Bits
Easy
- Word Frequency
Med.
- Valid Phone Numbers
Easy
- Transpose File
Med.
- Tenth Line
Easy
- Delete Duplicate Emails
Easy
- Rising Temperature
Easy
- House Robber
Med.
- Binary Tree Right Side View
Med.
- Number of Islands
-
- Assistant
Here is a simple and efficient Java solution to check if a number is an "ugly number" using the problem criteria:
To determine if a number ( n ) is an ugly number, you need to divide ( n ) by the prime factors 2, 3, and 5 until ( n ) can no longer be divided by these numbers. If you end up with ( n = 1 ), then it means all the prime factors of ( n ) are 2, 3, or 5, thus ( n ) is an ugly number.
Below is the Java code implementing the above logic:
class Solution { public boolean isUgly(int n) { if (n <= 0) { return false; } int[] primes = {2, 3, 5}; for (int prime : primes) { while (n % prime == 0) { n /= prime; } } return n == 1; } }Explanation:
- Check Initial Condition: If ( n ) is less than or equal to 0, it's not an ugly number as ugly numbers are positive integers.