首页 > 其他 > 详细

LeetCode 13 Roman to Integer(罗马数字转为整数)

时间:2017-03-03 23:03:09      阅读:286      评论:0      收藏:0      [点我收藏+]

 
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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!