https://leetcode.com/problems/roman-to-integer/description/
Solution 1. Use a map
int romanToInt(string s) {
unordered_map<char, int> R2I = {
{'I', 1}, {'V', 5}, {'X', 10}, {'L', 50}, {'C', 100}, {'D', 500}, {'M', 1000}
};
int res = 0;
for(int i=0; i<s.size();i++) {
if(i+1<s.size() && R2I[s[i]]<R2I[s[i+1]])
res -= R2I[s[i]];
else
res += R2I[s[i]];
}
return res;
}
Solution 2. Convert each char in s to the corresponding number first.
int romanToInt(string s) {
int res = 0;
int nums[s.size()];
for(int i=0; i<s.size();i++) {
switch(s[i]){
case 'I': nums[i] = 1; break;
case 'V': nums[i] = 5; break;
case 'X': nums[i] = 10; break;
case 'L': nums[i] = 50; break;
case 'C': nums[i] = 100; break;
case 'D': nums[i] = 500; break;
case 'M': nums[i] = 1000; break;
}
}
for(int i=0; i<s.size();i++) {
if(i+1<s.size() && nums[i]<nums[i+1])
res -= nums[i];
else
res += nums[i];
}
return res;
}
No comments:
Post a Comment