【LEET-CODE】12. Integer to Roman【Medium】

来源:互联网 发布:淘宝开店怎么实名认证 编辑:程序博客网 时间:2024/05/16 18:38

Qusetion:

Given an integer, convert it to a roman numeral.

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


思路:

把整数转成罗马数字,要仔细理解罗马数字的规则,如39应该对应XLI而不是IXL。

思路的话从到大到小不断整除取余,注意如果是900+,400+这类可能出现CM,CD之类倒序(M减去C)的情况,进行判定比较。

利用了递归调用本身,但是代码依然有些冗余,后续二刷时可尝试修改(负数情况也应考虑)。

但代码效率较高,32ms打败92.79%。

Code:

class Solution {public:    string intToRoman(int num) {        string s;        for(int i = num/1000; i>0 ; i-- ){            if(i>=4) return "";            s.push_back('M');        }        num = num % 1000;          for(int i = num/500; i>0 ; i-- ){            if(num < 900)                s.push_back('D');            else{                s.push_back('C');                s.push_back('M');                s= s + intToRoman(num-900);                return s;            }        }        num = num % 500;        for(int i = num/100; i>0 ; i-- ){            if(num < 400)                s.push_back('C');            else{                s.push_back('C');                s.push_back('D');                s= s + intToRoman(num-400);                return s;            }        }        num = num % 100;        for(int i = num/50; i>0 ; i-- ){            if(num < 90)                s.push_back('L');            else{                s.push_back('X');                s.push_back('C');                s= s + intToRoman(num-90);                return s;            }        }        num = num % 50;        for(int i = num/10; i>0 ; i-- ){            if(num < 40)                s.push_back('X');            else{                s.push_back('X');                s.push_back('L');                s= s + intToRoman(num-40);                return s;            }        }        num = num % 10;        for(int i = num/5; i>0 ; i-- ){            if(num < 9)                s.push_back('V');            else{                s.push_back('I');                s.push_back('X');                return s;            }        }        num = num % 5;        switch(num){            case 1:            s.push_back('I');            break;            case 2:            s.push_back('I');            s.push_back('I');            break;            case 3:            s.push_back('I');            s.push_back('I');            s.push_back('I');            break;            case 4:            s.push_back('I');            s.push_back('V');            break;                    }        return s;    }};


0 0
原创粉丝点击