zoukankan      html  css  js  c++  java
  • LeetCode--Ugly Number&&Ugly NumberⅡ--JavaScript&Java

    Ugly NumberⅡ

    Write a program to find the n-th ugly number.

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

    Note that 1 is typically treated as an ugly number.

    JavaScript
    /*
    * * @param {number} n * @return {number} */ var nthUglyNumber = function(n) { var l1 = new Array(0), l2 = new Array(0), l3 = new Array(0), i = 0, ans = 0; l1[0] = 1; l2[0] = 1; l3[0] = 1; for(i = 0;i < n;i ++){ ans = Math.min(Math.min(l1[0],l2[0]),l3[0]); if(l1[0] === ans){ l1.shift(); } if(l2[0] === ans){ l2.shift(); } if(l3[0] === ans){ l3.shift(); } l1.push(ans * 2); l2.push(ans * 3); l3.push(ans * 5); } return ans; };
    
    

    Java

    public class Solution {  
        public int nthUglyNumber(int n) {  
            int u = 0;  
            List<Integer> l1 = new LinkedList<Integer>();  
            List<Integer> l2 = new LinkedList<Integer>();  
            List<Integer> l3 = new LinkedList<Integer>();  
            l1.add(1);  
            l2.add(1);  
            l3.add(1);  
              
            for(int i=0; i<n; i++) {  
                u = Math.min( Math.min(l1.get(0), l2.get(0)), l3.get(0));  
                  
                if(l1.get(0) == u) l1.remove(0);  
                if(l2.get(0) == u) l2.remove(0);  
                if(l3.get(0) == u) l3.remove(0);  
                  
                l1.add(u*2);  
                l2.add(u*3);  
                l3.add(u*5);  
            }  
            return u;  
        }  
    } 

     Ugly Number:

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

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

    Note that 1 is typically treated as an ugly number.

    Credits:
    Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

    Subscribe to see which companies asked this question

    JavaScript
    /*
    * * @param {number} num * @return {boolean} */ var isUgly = function(num) { var i = 2; var temp = num; if(num <= 0) return false; if(num <= 6) return true; while(i * i <= num){ if(num % i === 0){ if(i > 5) return false; while(num % i === 0) num = num / i; } i ++; } if(num > 5) return false; return true; };
  • 相关阅读:
    redis常用方法
    分享朋友圈、qq等思路及代码
    redis 使用例子
    redis使用实例应用
    js对象与jquery对象介绍
    h5网页跳转到小程序
    redis队列思路介绍
    redis队列思路分析
    php原生方法连接mysql数据库
    mysql 原生语句limit 分页
  • 原文地址:https://www.cnblogs.com/Decmber/p/4922115.html
Copyright © 2011-2022 走看看