zoukankan      html  css  js  c++  java
  • 面试题34 丑数

    题目描述

    把只包含因子2、3和5的数称作丑数(Ugly Number)。例如6、8都是丑数,但14不是,因为它包含因子7。 习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第N个丑数。
     1 class Solution {
     2 public:
     3     int ugly;
     4     
     5     int min2(int a, int b){
     6         return a < b ? a : b;
     7     }
     8     
     9     int min(int a, int b, int c){
    10         return min2(a, min2(b, c));
    11     }
    12         
    13     int GetUglyNumber_Solution(int index) {
    14         if (index <= 0)
    15             return 0;
    16         int *pUglyNumbers = new int[index];
    17         pUglyNumbers[0] = 1;
    18         int nextUglyIndex = 1;
    19         int *pMultiply2 = pUglyNumbers;
    20         int *pMultiply3 = pUglyNumbers;
    21         int *pMultiply5 = pUglyNumbers;
    22         
    23         while (nextUglyIndex < index){
    24             int minNum = min(*pMultiply2 * 2, *pMultiply3 * 3, *pMultiply5 * 5);
    25             pUglyNumbers[nextUglyIndex] = minNum;
    26             while (*pMultiply2 * 2 <= pUglyNumbers[nextUglyIndex])
    27                 ++pMultiply2;
    28             while (*pMultiply3 * 3 <= pUglyNumbers[nextUglyIndex])
    29                 ++pMultiply3;
    30             while (*pMultiply5 * 5 <= pUglyNumbers[nextUglyIndex])
    31                 ++pMultiply5;
    32             ++nextUglyIndex;
    33         }
    34         
    35         ugly = pUglyNumbers[nextUglyIndex - 1];
    36         delete[] pUglyNumbers;
    37         return ugly;
    38     }
    39 };
  • 相关阅读:
    sql知识点记录
    makefile编译错误情况整理
    web worker 简介
    实现跨域访问的方法总结
    fiddler使用指南
    [转]SASS用法指南
    koa文档参考
    [转]html5: postMessage解决跨域和跨页面通信的问题
    [转]JavaScript ES6 class指南
    [转]前端利器:SASS基础与Compass入门
  • 原文地址:https://www.cnblogs.com/wanderingzj/p/5358388.html
Copyright © 2011-2022 走看看