标签:style blog class code java tar
一次通过:
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 };
Leetcode: Roman to Integer,布布扣,bubuko.com
标签:style blog class code java tar
原文地址:http://www.cnblogs.com/EdwardLiu/p/3715313.html