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);
    	}
    }
    
  • 相关阅读:
    HashMap 的数据结构
    JVM的内存区域划分
    分库分表的基本思想
    分表与分库使用场景以及设计方式
    千万数据的分库分表(一)
    用c++实现快速排序和归并排序
    如何查看python版本号?
    python的正则表达式
    python3的队列,比python2更好
    markdown如何插入代码?
  • 原文地址:https://www.cnblogs.com/harrygogo/p/4742531.html
Copyright © 2011-2022 走看看