首页 > 代码库 > Leetcode: Roman to Integer
Leetcode: Roman to Integer
一次通过:
1 public class Solution { 2 public int romanToInt(String s) { 3 int sum = 0; 4 int[] num = new int[s.length()]; 5 if(s == null) return 0; 6 for(int i=0; i<s.length(); ++i){ 7 char c = s.charAt(i); 8 if(c == ‘I‘) num[i] = 1; 9 if(c == ‘V‘) num[i] = 5; 10 if(c == ‘X‘) num[i] = 10; 11 if(c == ‘L‘) num[i] = 50; 12 if(c == ‘C‘) num[i] = 100; 13 if(c == ‘D‘) num[i] = 500; 14 if(c == ‘M‘) num[i] = 1000; 15 } 16 for(int j=1; j<num.length; ++j){ 17 if(num[j] > num[j-1]){ 18 num[j-1] = num[j]-num[j-1]; 19 num[j] = 0; 20 ++j; 21 } 22 } 23 for(int k=0; k<num.length; ++k){ 24 sum = sum + num[k]; 25 } 26 return sum; 27 } 28 }
别人一个用map的c++解法:(未深究)
1 class Solution { 2 public: 3 int romanToInt(string s) { 4 // Start typing your C/C++ solution below 5 // DO NOT write int main() function 6 map<char, int> S; 7 S[‘I‘] = 1; 8 S[‘V‘] = 5; 9 S[‘X‘] = 10; 10 S[‘L‘] = 50; 11 S[‘C‘] = 100; 12 S[‘D‘] = 500; 13 S[‘M‘] = 1000; 14 int ret = 0; 15 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]]; 16 return ret; 17 } 18 };
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。