今天做题的时候发现leetcode改版了,编译提交后可以看到所有的test cases。
leetcode的作者还是位华人,相当给力!
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
Solution:
The concept of roman numerals.
本解法的关键点在于特殊数字的表达(即相减: 9 = 10 -1; 90 = 100 -10; 40 = 50 -10. etc)只存在于2个字符之间。其余均为相加。
public class Solution {
public int charToNum (char c){
switch(c){
case 'I': return 1;
case 'V': return 5;
case 'X': return 10;
case 'L': return 50;
case 'C': return 100;
case 'D': return 500;
case 'M': return 1000;
default: return 0;
}
}
public int romanToInt(String s) {
// Start typing your Java solution below
// DO NOT write main() function
if(s==null || s.length() <= 0){
return 0;
}
int result = 0;
int pos = s.length() - 1;
while(pos >= 0){
if(pos-1 >= 0 && charToNum(s.charAt(pos)) > charToNum(s.charAt(pos-1))){
result += charToNum(s.charAt(pos)) - charToNum(s.charAt(pos-1));
pos -= 2;
}else{
result += charToNum(s.charAt(pos));
pos--;
}
}
return result;
}
}
2015-04-15 update python solution:
class Solution:
# @param s, a string
# @return an integer
def romanToInt(self, s):
romanDict = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
length = len(s)
if length == 1:
return romanDict[s]
result = romanDict[s[0]]
for i in range(1, length):
if romanDict[s[i]] > romanDict[s[i-1]]:
result = result - romanDict[s[i-1]] + (romanDict[s[i]] - romanDict[s[i-1]])
else:
result += romanDict[s[i]]
return result
s = Solution()
print s.romanToInt('M') == 1000
print s.romanToInt('MMM') == 3000
print s.romanToInt('MMMXXX') == 3030
print s.romanToInt('MMMCMXCIX') == 3999
print s.romanToInt('MMMCMXCVIII') == 3998
print s.romanToInt('MI') == 1001
print s.romanToInt('MMMIII') == 3003
print s.romanToInt('IV') == 4
print s.romanToInt('MMIX') == 2009
print s.romanToInt('MMMCDXLIX') == 3449