您的位置:首页 > 其它

LeetCode: Roman to Integer

2013-05-18 10:04 459 查看
看了别人答案

class Solution {
public:
int romanToInt(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
map<char, int> S;
S['I'] = 1;
S['V'] = 5;
S['X'] = 10;
S['L'] = 50;
S['C'] = 100;
S['D'] = 500;
S['M'] = 1000;
int ret = 0;
for (int i = 0; i < s.size(); i++) ret += (i>0 && S[s[i]] > S[s[i-1]])? S[s[i]]-2*S[s[i-1]] : S[s[i]];
return ret;
}
};


C#

public class Solution {
public int RomanToInt(string s) {
Dictionary<char, int> S = new Dictionary<char, int>();
S.Add('I', 1); S.Add('V', 5); S.Add('X', 10); S.Add('L', 50);
S.Add('C', 100); S.Add('D', 500); S.Add('M', 1000);
int ans = 0;
for (int i = 0; i < s.Length; i++) {
ans += (i > 0 && S[s[i]] > S[s[i-1]])? S[s[i]]-2*S[s[i-1]] : S[s[i]];
}
return ans;
}
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: