class Solution { public int romanToInt(String s) { s = s.replace("IV","a"); s = s.replace("IX","b"); s = s.replace("XL","c"); s = s.replace("XC","d"); s = s.replace("CD","e"); s = s.replace("CM","f"); int result = 0; for (int i=0; i<s.length(); i++) { result += which(s.charAt(i)); } return result; } public int which(char ch) { switch(ch) { case 'I': return 1; case 'V': return 5; case 'X': return 10; case 'L': return 50; case 'C': return 100; case 'D': return 500; case 'M': return 1000; case 'a': return 4; case 'b': return 9; case 'c': return 40; case 'd': return 90; case 'e': return 400; case 'f': return 900; } return 0; } }将这个代码转化为C++
时间: 2024-01-14 11:01:56 浏览: 121
以下是将该代码转换为 C++ 的版本:
```
class Solution {
public:
int romanToInt(string s) {
s = replaceAll(s, "IV", "a");
s = replaceAll(s, "IX", "b");
s = replaceAll(s, "XL", "c");
s = replaceAll(s, "XC", "d");
s = replaceAll(s, "CD", "e");
s = replaceAll(s, "CM", "f");
int result = 0;
for (int i = 0; i < s.length(); i++) {
result += which(s[i]);
}
return result;
}
private:
int which(char ch) {
switch(ch) {
case 'I': return 1;
case 'V': return 5;
case 'X': return 10;
case 'L': return 50;
case 'C': return 100;
case 'D': return 500;
case 'M': return 1000;
case 'a': return 4;
case 'b': return 9;
case 'c': return 40;
case 'd': return 90;
case 'e': return 400;
case 'f': return 900;
}
return 0;
}
string replaceAll(string str, string oldStr, string newStr) {
int pos = 0;
while ((pos = str.find(oldStr, pos)) != string::npos) {
str.replace(pos, oldStr.length(), newStr);
pos += newStr.length();
}
return str;
}
};
```
注意,在 C++ 中,字符串替换需要使用 `string::find()` 和 `string::replace()` 方法,因此需要单独定义一个 `replaceAll()` 函数来实现。
阅读全文