标签:man ring problems 字符 ret ant ble code class
字符串处理,完全是上一个题倒过来,同样从大到小干就可以了
class Solution {
public:
int romanToInt(string s) {
int ans = 0;
int k = 0;
while (k < s.size() && s[k] == ‘M‘) {
ans += 1000;
k++;
}
if (k < s.size() && s[k] == ‘C‘ && s[k + 1] == ‘M‘) {
ans += 900;
k += 2;
}
if (k < s.size() && s[k] == ‘C‘ && s[k + 1] == ‘D‘) {
ans += 400;
k += 2;
}
if (k < s.size() && s[k] == ‘D‘) {
ans += 500;
k++;
}
while (k < s.size() && s[k] == ‘C‘) {
ans += 100;
k++;
}
if (k < s.size() && s[k] == ‘X‘ && s[k + 1] == ‘C‘) {
ans += 90;
k += 2;
}
if (k < s.size() && s[k] == ‘X‘ && s[k + 1] == ‘L‘) {
ans += 40;
k += 2;
}
if (k < s.size() && s[k] == ‘L‘) {
ans += 50;
k++;
}
while (k < s.size() && s[k] == ‘X‘) {
ans += 10;
k++;
}
if (k < s.size() && s[k] == ‘I‘ && s[k + 1] == ‘X‘) {
ans += 9;
k += 2;
}
if (k < s.size() && s[k] == ‘I‘ && s[k + 1] == ‘V‘) {
ans += 4;
k += 2;
}
if (k < s.size() && s[k] == ‘V‘) {
ans += 5;
k++;
}
while (k < s.size() && s[k] == ‘I‘) {
ans += 1;
k++;
}
return ans;
}
};
标签:man ring problems 字符 ret ant ble code class
原文地址:https://www.cnblogs.com/acbingo/p/9231692.html