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

[leetcode] Roman to Integer

时间:2014-06-27 12:33:17      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:class   blog   code   java   http   tar   

Given a roman numeral, convert it to an integer.

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

https://oj.leetcode.com/problems/roman-to-integer/

思路1:从前向后遍历罗马数字,如果某个数比前一个数小,则加上该数。反之,减去前一个数的两倍然后加上该数。

public class Solution {

    public int romanToInt(String s) {
        char[] symbol = { ‘I‘, ‘V‘, ‘X‘, ‘L‘, ‘C‘, ‘D‘, ‘M‘ };
        int[] val = { 1, 5, 10, 50, 100, 500, 1000 };
        Map<Character, Integer> map = new HashMap<Character, Integer>();
        for (int i = 0; i < symbol.length; i++)
            map.put(symbol[i], val[i]);

        int len = s.length();
        int res = 0;

        res += map.get(s.charAt(0));
        for (int i = 1; i < len; i++) {
            int cur = map.get(s.charAt(i));
            int pre = map.get(s.charAt(i - 1));
            if (cur <= pre) {
                res += cur;
            } else {
                res = res + cur - 2 * pre;
            }

        }
        return res;

    }

    public static void main(String[] args) {
        System.out.println(new Solution().romanToInt("MCMXC"));
    }
}

 

 

参考:

http://blog.csdn.net/wzy_1988/article/details/17057929

 

 

 

 

 

[leetcode] Roman to Integer,布布扣,bubuko.com

[leetcode] Roman to Integer

标签:class   blog   code   java   http   tar   

原文地址:http://www.cnblogs.com/jdflyfly/p/3810686.html

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