LeetCode-Integer to Roman

 题目:

  Given an integer, convert it to a roman numeral.

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

 

题目分析:

    看了半天,题目都没看懂,都不知道了roman numeral是什么东西.于是在网上查了下,才明白是个什么东东,表示很无语.

模拟题:

                    基本字符 I V X L C D M
           相应的阿拉伯数字表示含义 1 5 10 50 100 500 1000

1.相同的数字连写,所表示的数等于这些数字相加得到的数,如:III =3;

2.小的数字在大的数字的左边,则所表示的数等于大数减小的数得到的数.如:IV=4;iX=9;

3.小的数字在大的数字的右边,则所表示的数等于大数加上小的数得到的数.如:VI=6;XI=11;

代码:

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);
                }
           }
           
           else if(n==4){
                 res.push_back(a);
                 res.push_back(b);
           }
           
           else if(n==5){
                 res.push_back(b);
           }
           
           else if(n>5 && n<9){
                  res.push_back(b);
                  for(int i=5;i<n;i++){
                        res.push_back(a);
                  }
          }
          
          else if(n==9){
              res.push_back(a);
              res.push_back(c);
          }
    }
    
    string intToRoman(int num){
          int a1=(num/1000)%10,a2=(num/100)%10,a3=(num/10)%10,a4=num%10;
          setDigit(res,a1,'M','?','?');
          setDigit(res,a2,'C','D','M');
          setDigit(res,a3,'X','L','C');
          setDigit(res,a4,'I','V','X');
          return res;
    }
};

 参考别人写的...

posted @ 2014-09-30 17:29  晓风_7  阅读(226)  评论(0编辑  收藏  举报