每日leecode-Integer to Roman

3,007次阅读
没有评论

共计 1199 个字符,预计需要花费 3 分钟才能阅读完成。

罗马数字的计数规则

  1. 相同的数字连写、所表示的数等于这些数字相加得到的数、如:Ⅲ=3;
  2. 小的数字在大的数字的右边、所表示的数等于这些数字相加得到的数、 如:Ⅷ=8、Ⅻ=12;
  3. 小的数字、(限于 Ⅰ、X 和 C)在大的数字的左边、所表示的数等于大数减小数得到的数、如:Ⅳ=4、Ⅸ=9;
  4. 正常使用时、连写的数字重复不得超过三次;
  5. 在一个数的上面画一条横线、表示这个数扩大 1000 倍

代码实现:

百度百科给的答案:

该答案通过建表的方式把所有的可能出现的异常点全部包含进来,然后查表实现。

比如9,答案应该是IX,如果正常处理就要考虑跟1,5,10之间的关系,需要写相关的判定,一定程度上增加了代码量

class Solution {
public:
    string 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"}
        };
        string roman;
        roman.append(c[3][num / 1000 % 10]);
        roman.append(c[2][num / 100 % 10]);
        roman.append(c[1][num / 10 % 10]);
        roman.append(c[0][num % 10]);
         
        return roman;
    }
};
 

leetcode提交的代码:

class Solution {
public:
    void setDigit(string &res, int n, char a, char b, char c) {
         if (n < 4) 
         {
            for (int i = 0; i < n; ++i) 
            {   
              res.push_back(a);             
            }         
         }         
         if (n == 4)
         {            
            res.push_back(a);             
            res.push_back(b);        
         }         
         if (n == 5) 
           res.push_back(b);         
         if (n > 5 && n < 9) 
         {
            res.push_back(b);
            for (int i = 5; i < n; ++i) {
                res.push_back(a);
            }
        }
        if (n == 9) {
            res.push_back(a);
            res.push_back(c);
        }
    }
    string intToRoman(int num) {
        int t = (num / 1000) % 10, h = (num / 100) % 10, d = (num / 10) % 10, n = num % 10;
        string res;
        setDigit(res, t, 'M', '?', '?');
        setDigit(res, h, 'C', 'D', 'M');
        setDigit(res, d, 'X', 'L', 'C');
        setDigit(res, n, 'I', 'V', 'X');
        return res;
    }
};
正文完
请博主喝杯咖啡吧!
post-qrcode
 
admin
版权声明:本站原创文章,由 admin 2016-04-24发表,共计1199字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
评论(没有评论)
验证码