LeetCode #263 Ugly Number Solution & Explanation

LeetCode Problem

An ugly number is a positive integer whose prime factors are limited to 23, and 5.

Given an integer n, return true if n is an ugly number.


Solution

To check if a number is ugly, we repeatedly divide it by 2, 3, and 5 if it is divisible by any of these numbers. We return ‘true‘ if the number becomes 1 after all such divisions, indicating that it is an ugly number. Otherwise, we return ‘false‘.

C# Solution

Solution1

public class Solution {
    public bool IsUgly(int n) {
        if(n<=0){
            return false;
        }
        while(true){
            if(n%2==0){
                n/=2;
            }
            else if(n%3==0){
                n/=3;
            }
            else if(n%5==0){
                n/=5;
            }
            else if(n==1){
                return true;
            }
            else{
                return false;
            }
        }
    }
}

Java Solution

Solution1

class Solution {
    public boolean isUgly(int n) {
        if(n<=0){
            return false;
        }
        while(true){
            if(n%2==0){
                n/=2;
            }
            else if(n%3==0){
                n/=3;
            }
            else if(n%5==0){
                n/=5;
            }
            else if(n==1){
                return true;
            }
            else{
                return false;
            }
        }
    }
}

Conclusion

🧡If my solution helps, that is my honor!

🧡You can support me by sharing my posts, thanks a lot

If you got any problem about the explanation, please feel free to let me know

The problem link : Ugly Number – LeetCode

Some Random LeetCode posts

Leave a Reply

Your email address will not be published. Required fields are marked *