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; };
  • 相关阅读:
    如何把新加的分区挂载到指定目录下
    怎样通过U盘安装启动Centos6.8
    Redis 单机安装【一】
    Linux漏洞扫描工具【lynis】
    mysql 主从 重新同步
    Centos 6.8下安装oracle10g数据库、
    监控服务supervisor服务的安装及使用
    制作c#桌面应用程序 安装程序 卸载程序
    Microsoft Visual SourceSafe 2005 服务端安装配置过程以及出现的问题,以及解决方法!
    .NET中的CSV导入导出
  • 原文地址:https://www.cnblogs.com/Decmber/p/4922115.html
Copyright © 2011-2022 走看看