码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode -- Roman to Integer

时间:2015-09-01 21:26:33      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:

Question: Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

Analysis: 该问题是将输入的罗马数字的字符串转化为整数。 方法:从左到右依次扫描字符串,需要三个变量:temp记录分段数字, lastv表示刚刚扫描过的数字, curv表示当前正在扫描的数字。

1. 若lastv == curv,则记录变量加上当前字符;

2. 若lastv < curv,则当前字符减去记录变量记录下的值;

3.若lastv > curv,记录变量直接加到结果中。

Answer:

public class Solution {
        public int romanToInt(String s) {
        if(s == null || s.length() == 0)
            return 0;
        int sum = 0;
        int temp = charToInt(s.charAt(0));
        int lastv = temp;
        for(int i=1; i<s.length(); i++){
            char c = s.charAt(i);
            int curv = charToInt(c);
            
            if(lastv == curv)
                temp += curv;
            else if(lastv < curv){
                temp = curv - temp;
            } else {
                sum += temp;
                temp = curv;
            }
            lastv = curv;
        }
        sum += temp;
        return sum;
        
    }
    
    private int charToInt(char c) {
        // TODO Auto-generated method stub
        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;
        }
    }
}

 

LeetCode -- Roman to Integer

标签:

原文地址:http://www.cnblogs.com/little-YTMM/p/4776671.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!