每周一道算法题(八)

作者: CrazySteven | 来源:发表于2017-05-06 21:54 被阅读624次

    本周的题目是一道经典题,难度级别"Medium"...

    题目:将1~3999的阿拉伯数字转化为罗马数字。

    这题还是比较经典的,做这题之前要先了解一下罗马数字,然后看看实现代码:

    char* intToRoman(int num) {
        int numArr[] = {1000,900,500,400,100,90,50,40,10,9,5,4,1};
        char *numRoman[] = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
        char *numResult = malloc(100);
        
        for(int i=0; i<sizeof(numArr)/sizeof(int); i++){
            while(num >= numArr[i]){
                strcat(numResult,numRoman[i]);
                num -= numArr[i];
            }
        }
        return numResult;
    }
    

    百度百科的罗马数字里面就有这道经典的算法题,不过里面是用C++写的,在这里我也翻译成C,顺便用了个for循环,不易出错:

    char* intToRoman(int num) 
        char* c[4][10]={
            {"","I","II","III","IV","V","VI","VII","VIII","IX"},
            {"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"},
            {"","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"},
            {"","M","MM","MMM"}
        };
        char *roman = malloc(100);
        for (int i = 3; i >= 0; i--) {
            int temp = pow(10, i);
            strcat(roman, Roman[i][num / temp % 10]);
        }
    }
    

    版权声明:本文为 Crazy Steven 原创出品,欢迎转载,转载时请注明出处!

    相关文章

      网友评论

        本文标题:每周一道算法题(八)

        本文链接:https://www.haomeiwen.com/subject/byuytxtx.html