1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
#include <iostream> using namespace std; bool IsUgly(int number) { while (number % 2 == 0) { number /= 2; } while (number % 3 == 0) { number /= 3; } while (number % 5 == 0) { number /= 5; } return (number == 1) ? true : false; } int GetUglyNumber(int index) { if (index <= 0) { return 0; } int number = 0; int uglyFound = 0; while (uglyFound < index) { //number一直在累加,while判断的是uglyFound ++number; if (IsUgly(number)) { ++uglyFound; } } return number; } int main() { cout << GetUglyNumber(15) << endl; return 0; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
#include <iostream> using namespace std; int Min(int number1, int number2, int number3) { int min = (number1 < number2) ? number1 : number2; min = (min < number3) ? min : number3; return min; } int GetUglyNumber(int index) { if (index <= 0) { return 0; } int *pUglyNumbers = new int[index]; pUglyNumbers[0] = 1; int nextUglyIndex = 1; int *pMultiply2 = pUglyNumbers; int *pMultiply3 = pUglyNumbers; int *pMultiply5 = pUglyNumbers; while (nextUglyIndex < index) { int min = Min(*pMultiply2 * 2, *pMultiply3 * 3, *pMultiply5 * 5); pUglyNumbers[nextUglyIndex] = min; while (*pMultiply2 * 2 <= pUglyNumbers[nextUglyIndex]) { ++pMultiply2; } while (*pMultiply3 * 3 <= pUglyNumbers[nextUglyIndex]) { ++pMultiply3; } while (*pMultiply5 * 5 <= pUglyNumbers[nextUglyIndex]) { ++pMultiply5; } ++nextUglyIndex; } int ugly = pUglyNumbers[nextUglyIndex - 1]; delete[] pUglyNumbers; return ugly; } int main() { cout << GetUglyNumber(15) << endl; return 0; } |
原文地址:http://www.cnblogs.com/codemylife/p/3747046.html