13. Roman to Integer C++
阿新 • • 發佈:2018-11-12
+= png rom 循環 ger cout spa 分享 ==
直接for循環,並且判斷是否出現IV等情況
int which(char ch) { if(ch == ‘I‘) return 1; else if(ch == ‘V‘) return 5; else if(ch == ‘X‘) return 10; else if(ch == ‘L‘) return 50; else if(ch == ‘C‘) return 100; else if(ch == ‘D‘) return 500; else return1000; } class Solution { public: int romanToInt(string s) { int flag = 0; int ans = 0; for(int i=0; i<s.size(); i++) { if(i != s.size()-1 && which(s.at(i)) < which(s.at(i+1))) { flag = 1; }if(flag) { ans -= which(s.at(i)); flag = 0; } else ans += which(s.at(i)); } cout << ans; return ans; } };
13. Roman to Integer C++