Ugly number I and II Leetcode

Source: Internet
Author: User

Write a program to check whether a given number is a ugly number.

Ugly numbers are positive numbers whose the prime only include 2, 3, 5. For example, 6, 8 are ugly while are not ugly since it includes another prime factor 7.

Note This 1 is typically treated as a ugly number.

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

Ugly number II Total accepted:5494 Total submissions:28717 My submissions question Solution
Write a program to find the n-th ugly number.

Ugly numbers are positive numbers whose the prime only include 2, 3, 5. For example, 1, 2, 3, 4, 5, 6, 8, 9, ten, is the sequence of the The ugly numbers.

Note This 1 is typically treated as a ugly number.

public class Solution {public int nthuglynumber (int n) {Priorityqueue<integer> ;
        Queue=new priorityqueue<integer> ();
        Queue.add (1);
        int pre=0;
            for (int i=1;i<n;i++) {int cur = queue.poll ();
                if (cur==pre) {i--;
            Continue
                } if (cur*2>0) {queue.add (cur*2);
                    if (cur*3>0) {queue.add (cur*3);
                if (cur*5>0) Queue.add (cur*5);
        }} pre=cur;
        while (Queue.peek () ==pre) {queue.poll ();
    return Queue.peek (); }
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.