力扣(LeetCode)试题13-罗马数字转整数 C++代码

新手,不关乎复杂度,力扣练手,训练自己的编码思维,追求功能实现。随笔

 

 1 #include <iostream>
 2 #include <string>
 3 
 4 using namespace std;
 5 
 6 int getValue(char c);
 7 
 8 class Solution{
 9 public:
10     int romanToInt(string s){
11         int sum = 0;
12         int val = s.length();
13         for (int i = 0; i<val-1; i++){
14             if (getValue(s[i])>=getValue(s[i+1]))
15                 sum += getValue(s[i]);
16             else
17                 sum -= getValue(s[i]);
18             }
19         sum += getValue(s[val - 1]);
20         return sum;
21     }
22 };
23 
24 int getValue(char c){
25     switch (c)
26     {
27     case('I') :
28         return 1;
29     case('V') :
30         return 5;
31     case('X') :
32         return 10;
33     case('L') :
34         return 50;
35     case('C') :
36         return 100;
37     case('D') :
38         return 500;
39     case('M') :
40         return 1000;
41     //default:
42         //return -1;
43         //break;
44     }
45 }
46 
47 int main(){
48     Solution sol;
49     string str = "MCMXCIV";
50     int p,q;
51     p = sol.romanToInt(str);
52     cout << p << endl;
53     cin >> q;
54     return 0;
55 }

 

 

posted @ 2020-06-30 12:41  ZyLin-ux  阅读(135)  评论(0编辑  收藏  举报