zoukankan      html  css  js  c++  java
  • Ugly Number

    Problem I

    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.

    程序

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

    Problem II

    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.

    解决思路

    我们可以发现每一个子列表都是丑陋数本身(1, 2, 3, 4, 5, …) 乘以 2, 3, 5

    接下来我们使用与归并排序相似的合并方法,从3个子列表中获取丑陋数。每一步我们从中选出最小的一个,然后向后移动一步。

    程序

    public class Solution {
        public int nthUglyNumber(int n) {
    		if (n <= 0) {
    			return 0;
    		}
    
    		List<Integer> list = new ArrayList<Integer>();
    		list.add(1);
    		
    		int i2 = 0, i3 = 0, i5 = 0;
    
    		while (list.size() < n) {
    			int n2 = list.get(i2) * 2;
    			int n3 = list.get(i3) * 3;
    			int n5 = list.get(i5) * 5;
    			int m = Math.min(Math.min(n2, n3), n5);
    			
    			if (m == n2) {
    				++i2;
    			} 
    			if (m == n3) {
    				++i3;
    			} 
    			if (m == n5) {
    				++i5;
    			}
    			
    			list.add(m);
    		}
    
    		return list.get(n - 1);
    	}
    }
    
  • 相关阅读:
    转载:PHP的session过期设置
    转载:php实现记住密码自动登录
    jQuery方法大全
    转载: IE、FF、Safari、OP不同浏览器兼容报告
    div布局的小心得
    PHP MVC模式在网站架构中的实现分析
    梳理一下 html 中的一些基本概念
    DNN学习笔记代码学习:Null 荣
    DNN学习笔记:DNN类中的ProviderType字段 荣
    在苏州 荣
  • 原文地址:https://www.cnblogs.com/harrygogo/p/4742531.html
Copyright © 2011-2022 走看看