• 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; };
  • 相关阅读:
    ros 使用命令测试topic
    python unicode
    python ros 回充demo
    python ros 回充调用demo
    flask报错No module named 'flask.ext'
    python flask 接口
    ros 安装c++编译的可执行文件
    Linux-Ubuntu14.04下mongodb安装部署
    如何在Ubuntu 14.04中安装最新版Eclipse
    ubuntu 14.04 安装redis5.0.3
  • 原文地址:https://www.cnblogs.com/Decmber/p/4922115.html
Copyright © 2020-2023  润新知