Created
December 19, 2014 17:12
-
-
Save wangchauyan/656c0681c049a6525e24 to your computer and use it in GitHub Desktop.
Roman String to Integer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package wcy.leetcode.gist; | |
/** | |
* Created by ChauyanWang on 12/20/14. | |
*/ | |
public class romanToInt { | |
int getInteger(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; | |
} | |
return 0; | |
} | |
public int Solution (String s) { | |
if(s == null || s.length() == 0) return 0; | |
s = s.toLowerCase(); | |
int result = 0; | |
int index = 0; | |
while (index < s.length()) { | |
if(index + 1 != s.length()-1 && | |
getInteger(s.charAt(index)) < getInteger(s.charAt(index+1))) { | |
result += getInteger(s.charAt(index-1)) - getInteger(s.charAt(index)); | |
index += 2; | |
} else { | |
result += getInteger(s.charAt(index)); | |
index++; | |
} | |
} | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment