• 编程算法


    数丑陋 代码(C)


    本文地址: http://blog.csdn.net/caroline_wendy


    题目: 我们把仅仅包括因子2, 3 和 5的数称作丑数. 求按从小到大的顺序的第5个丑数.


    能够设置一个数组包括所须要的丑数, 依次比較乘以2, 乘以3, 乘以5的最小的数, 最后返回结果.

    如第5个丑数是5, 如1, 2, 3, 4(2*2), 5均是丑数.


    代码:

    /*
     * main.cpp
     *
     *  Created on: 2014.6.12
     *      Author: Spike
     */
    
    /*eclipse cdt, gcc 4.8.1*/
    
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    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(void)
    {
        int num = 5;
        int result = GetUglyNumber(num);
        printf("result = %d
    ", result);
    
        return 0;
    }
    

    输出:

    result = 5
    







    版权声明:本文博主原创文章,博客,未经同意不得转载。

  • 相关阅读:
    Android Wifi BT的工作流程和porting(精)
    ioctl命令详解
    android 编译库过程
    git恢复repo start 后丢失的修改记录
    Android Bluetooth 分析(精)
    SDIO总线 驱动
    提取高通最新代码patch
    linux设备驱动——andriod平台wlan驱动
    推送现有git到远程服务器并创建新分支
    c++继承经典例子
  • 原文地址:https://www.cnblogs.com/bhlsheji/p/4853909.html
Copyright © 2020-2023  润新知