leetcode No12. Integer to Roman

来源:互联网 发布:网络电视哪个型号好 编辑:程序博客网 时间:2024/06/06 01:21

Question:

Given an integer, convert it to a roman numeral.

Input is guaranteed to be within the range from 1 to 3999.

即把数字转换成罗马数字

Algorithm:

按照罗马数字的规则转换即可,wikipedia有详细解释

Accepted Code:

class Solution {public:    string intToRoman(int num) {        string s;//        map<int,char> hash;//        hash[1000] = 'M';//        hash[500]  = 'D';//        hash[100]  = 'C';//        hash[50]   = 'L';//        hash[10]   = 'X';//        hash[5]    = 'V';//        hash[1]    = 'I';        int n1=num/1000;        while(n1)        {            s.push_back('M');            n1--;        }        num=num%1000;        if(num>=900)        {            s.push_back('C');            s.push_back('M');            num = num-900;        }        else if(num>=500)        {            s.push_back('D');            num = num-500;        }        if(num>=400)        {            s.push_back('C');            s.push_back('D');            num=num-400;        }        else        {            int n2=num/100;            while(n2)            {                s.push_back('C');                n2--;            }            num=num%100;        }        if(num>=90)        {            s.push_back('X');            s.push_back('C');            num = num-90;        }        else if(num>=50)        {            s.push_back('L');            num = num-50;        }        if(num>=40)        {            s.push_back('X');            s.push_back('L');            num=num-40;        }        else        {            int n3=num/10;            while(n3)            {                s.push_back('X');                n3--;            }            num=num%10;        }        if(num>=9)        {            s.push_back('I');            s.push_back('X');            num = num-9;        }        else if(num>=5)        {            s.push_back('V');            num = num-5;        }        if(num>=4)        {            s.push_back('I');            s.push_back('V');            num=num-4;        }        else        {            int n4=num;            while(n4)            {                s.push_back('I');                n4--;            }        }        return s;    }};




0 0
原创粉丝点击