RomanToInteger

package leetcode;

import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class RomanToInteger {
    public int romanToInt(String s) {
        Map<String,Integer> map = this.setRules();
        int num = 0;
        List<Integer> result = new ArrayList<>();
        for (int i = 0; i < s.length(); i++){
            result.add(map.get(s.substring(i,i+1)));
        }
        for (int j = 0; j < result.size(); j++){
            if (j == result.size() -1) num += result.get(j);
            else if (result.get(j) >= result.get(j + 1)) num += result.get(j);
            else num -= result.get(j);
        }
        return num;
    }

    private Map<String,Integer> setRules(){
        Map<String,Integer> map = new HashMap<>();
        map.put("I",1);
        map.put("V",5);
        map.put("X",10);
        map.put("L",50);
        map.put("C",100);
        map.put("D",500);
        map.put("M",1000);
        return map;
    }

    public static void main(String[] args) {
        RomanToInteger rti = new RomanToInteger();
        System.out.println(rti.romanToInt("I"));
    }
}

阅读更多
文章标签: leetcode
上一篇ReverseInteger
下一篇PalindromeNumber
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭