牛客网在线编程专题《剑指offer-面试题34》丑数

版权声明:本文为博主原创文章,欢迎大家转载,但是要注明我的文章地址。 https://blog.csdn.net/program_developer/article/details/82690745

题目链接:

https://www.nowcoder.com/practice/6aa9e04fc3794f68acf8778237ba065b?tpId=13&tqId=11186&tPage=2&rp=2&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

题目描述:

解题思路:

(1)逐个判断整数是不是丑数的解法

所谓一个数m是另一个数n的因子,是指n能被m整除,也就是n%m==0。根据丑数的定义,丑数只能被2,3和5整除。也就是说如果一个数能被2整除,我们把它连续除以2;如果能被3整除,就连续除以3;如果能被5整除,就连续除以5。如果最后我们得到的是1,那么这个数就是丑数,否则就不是。接下来,我们只需要按照顺序判断每一个整数是不是丑数即可。

代码:

import java.util.Scanner;

public class ugleNum {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		System.out.println(GetUglyNumber_Solution(n));
	}
	
	 public static int GetUglyNumber_Solution(int index) {
			int  i = 0;
			int count = 0;
			while(count< index) {
					i++;
					if(isUgleNum(i)) {
						count++;
					}
				}
				return i;
	 }
	
	public static boolean isUgleNum(int num) {
		while(num%2 == 0) {
			num = num /2;
		}
		while(num%3 == 0) {
			num = num /3;
		}
		while(num%5 == 0) {
			num = num /5;
		}
		if(num ==1) {
			return true;
		}else {
			return false;
		}
	}

}

(2)创建数组保存已经找到的丑数,用空间换时间的解法

猜你喜欢

转载自blog.csdn.net/program_developer/article/details/82690745
今日推荐