int toNumber(char ch) {
switch (ch) {
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;
}
package leetcode_50;
/***
*
* @author pengfei_zheng
* 罗马数字转为整数
*/
public class Solution13 {
public int romanToInt(String s) {
int len = s.length();
int ans = toNumber(s.charAt(len-1));
for(int i=len-2;i>=0;i--){
int last = toNumber(s.charAt(i+1));
int first = toNumber(s.charAt(i));
if(first>=last){//后面字符单位小于前面字符单位,加上对应数字
ans+=first;
}
else//减去对应数字
ans-=first;
}
return ans;
}
int toNumber(char ch) {//对应转换规则
switch (ch) {
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;
}
}
LeetCode 13 Roman to Integer(罗马数字转为整数)
原文:http://www.cnblogs.com/zpfbuaa/p/6498573.html