返回列表 發帖
  1. #include <iostream>
  2. #include <cstdlib>
  3. #include <cstring>
  4. #define N 7

  5. using namespace std ;

  6. string roman[N] = {"M", "D", "C", "L", "X", "V", "I"};
  7. int arabic[N] = {1000, 500, 100, 50, 10, 5, 1};
  8.    
  9. int to_int(string s){
  10.     int tmp =0 ;
  11.     int m = 0 ;
  12.     for(int i=0;i<s.length();i++){
  13.         for(int j=0;j<N;j++){
  14.             string c = s.substr(i,1) ;
  15.             if( roman[j]== c){
  16.                 tmp += arabic[j];
  17.                 break;
  18.             }   
  19.         }
  20.     }
  21.     return tmp ;
  22. }
  23. string to_roman(int ab){
  24.     if(ab==0){
  25.         return "ZERO";         
  26.     }
  27.     string tmp ;
  28.     int t ;
  29.     for(int i=0;i<N;i+=2){
  30.         t = ab/arabic[i];
  31.         if(t==9||t==4){
  32.             int les = arabic[i-2] - t*arabic[i];
  33.             for(int j=0;j<N;j++){
  34.                 if(arabic[j]==les){
  35.                     tmp += roman[j];
  36.                     break;                  
  37.                 }  
  38.             }
  39.             tmp+=roman[i-2];
  40.         }else{
  41.               if(t>4){
  42.                    tmp += roman[i-1];
  43.                    t-=5 ;
  44.               }
  45.               for(int z=0;z<t;z++){
  46.                       tmp+=roman[i];
  47.               }
  48.         }
  49.         ab %= arabic[i];
  50.     }
  51.     return tmp ;
  52. }
  53. int main(){
  54.    
  55.     string s = "MM";
  56.     string s2 = "II" ;
  57.     int a ,b ;
  58.     a = to_int(s);
  59.     b = to_int(s2);
  60.     cout << to_roman(a-b) ;
  61.    
  62.     cout << endl ;
  63.     system("pause");
  64. }
複製代碼

TOP

返回列表