[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
Note that
Analysis:
Solution:
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, 8are ugly while
14is not ugly since it includes another prime factor
7.
Note that
1is 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; } }
相关文章推荐
- [LeetCode#204]Factorial Trailing Zeroes
- xml解析及编译汇总 valgrind检测内存泄露 http://blog.csdn.net/lifan5/article/details/8030285
- Drainage Ditches 最大流入门练习题,各种算法
- ld: library not found for -lAFNetworking clang: error: linker command failed with exit code 1 (use -
- [LeetCode#172]Factorial Trailing Zeroes
- 【转】使用AIDL实现进程间的通信之复杂类型传递
- 错误 1 error LNK2019: 无法解析的外部符号 _WinMain@16,该符号在函数 ___tmainCRTStartup 中被引用
- HDU 1702 ACboy needs your help again!(模拟 队列 栈)
- 浅谈raid各个级别的特性
- 博客8:RAID阵列的实现
- RAII
- hdu4300 Clairewd’s message(扩展KMP)
- LeetCode之Container With Most Water
- leetcode-172-Factorial Trailing Zeroes
- Aircrack-ng之aireplay(Deauthentication)
- LeetCode之Contains Duplicate II
- 什么情况下用copy、assign、retain、strong...
- 车型识别“A Large-Scale Car Dataset for Fine-Grained Categorization and Verification”
- 刷一题Leetcode:Factorial Trailing Zeroes
- LeetCode之Contains Duplicate