[LeetCode]013. Roman to Integer
今日問題をする時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文字の間にしか存在しないことにある.残りは加算されます.
2015-04-15 update python solution:
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