您的位置:首页 > 大数据 > 人工智能

[LeetCode#263]Factorial Trailing Zeroes

2015-09-01 04:24 549 查看
Problem:

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.

Analysis:

This problem is simple, but you may run into a complexty and easy-wrong way.
The below is a complex solution(wrong) try to use the same idea from "count primes".

A complex and wrong solution:
public class Solution {
public boolean isUgly(int num) {
if (num <= 0)
return true;
// throw new IllegalArgumentException("The passed in argument is not legal");
if (num == 1)
return true;
boolean[] check_board = new boolean[num+1];
Arrays.fill(check_board, true);
for (int i = 2; i <= Math.sqrt(num); i++) {
if (check_board[i] == true) {
for (int j = i*2; j <= num; j = j+i) {
check_board[j] = false;
if (j == num) {
if (!(i == 2 || i == 3 || i== 5)))
return true;
}
}
}
}
return false;
}
}

Why we so many uncessary computing and memeory reasource for a sigle number???
(Something must be wrong for the solution)

If a number is a ugly number, if must consist of (2, 3 5) through following way.
num = (2^i) * (3^j) * (5^k) * 1

Why not we strip out prime factor(2, 3, 5) one by one from num, then check if "num == 1"?
How to strip out prime factor from a integer?
Assume: a is the prime factor
while (num % a == 0) {
num = num / a;
}
Reason: since num could be fully divided by a (num % a == 0), we could still strip a from num.
This idea is very tricky compared with our past experience in using array. Take care!


Solution:

public class Solution {
public boolean isUgly(int num) {
if (num <= 0)
return false;
if (num == 1)
return true;
int[] x = {2, 3, 5};
for (int a : x) {
while (num % a == 0) {
num = num / a;
}
}
return num == 1;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: