<LeetCode> 题4:丑数
2016-07-12 09:47
453 查看
题目描述:
设计一个算法,找出只含素因子2,3,5 的第 n 大的数。符合条件的数如:1, 2, 3, 4, 5, 6, 8, 9, 10, 12…
注意:1也是丑数
例如:输入9,则输出10
思路一:暴力解法
从1开始依次向后判断各自然数是否为丑数,一直判断到第n个丑数,返回第n个丑数的值。第一步:先判断每一个数m是否为丑数:可以试着用2、3、5不断整除m,当m不能再被2、3、5整除时,判断m是否等于1,等于1则指定的数字是丑数(返回真),否则不是(返回假)。
判断是否为丑数的方法:对一个数重复除以2,3,5直到这个数不存在2,3,5这三个因子为止,若此时得到的结果不为1,则说明该数不是丑数。
写法一:
bool isUgly(int num) { if (num<= 0) return false; if (num == 1) return true; while (num>= 2 &&num % 2 == 0) num /= 2; while (num>= 3 &&num % 3 == 0) num /= 3; while (num>= 5 &&num % 5 == 0) num /= 5; return num == 1; }
写法二:
bool isUgly(int num) { if(num< 1) return false; if(num == 1) return true; vector<int> num_vect; num_vect.push_back(2); num_vect.push_back(3); num_vect.push_back(5); for(size_t i=0; i!=num_vect.size();++i) { while(num % num_vect[i] == 0) { num = num/num_vect[i]; } } if(num == 1) return true; else return false; }
第二步:从1开始,一直判断到第n个丑数为止,返回第n个丑数的值即可。
int nthUglyNumber(int n) { if(n<= 1) return 1; int count = 0; for(int i = 1; ; i++) { if(isUgly(i)) { count++; if(count == n) return i; } } }
完整程序:
#include<iostream> #include<vector> using namespace std; bool isUgly(int num) { if(num< 1) return false; if(num == 1) return true; vector<int> num_vect; num_vect.push_back(2); num_vect.push_back(3); num_vect.push_back(5); for(size_t i=0; i!=num_vect.size();++i) { while(num % num_vect[i] == 0) { num = num/num_vect[i]; } } if(num == 1) returntrue; else returnfalse; } class Solution { public: int nthUglyNumber(int n) { if(n<= 1) return 1; int count = 0; for(int i = 1; ; i++) { if(isUgly(i)) { count++; if(count == n) return i; } } } }; int main() { Solution st; cout<<"第9个丑数为:"<<st.nthUglyNumber(9) <<endl; system("pause"); return 0; }
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解