# 罗马数字转整数(leetcode-13)

static int[] values = {1000,900,500,400,100,90,50,40,10,9,5,4,1};
static String[] symbols = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};

输入: "III"

import java.util.*;

class Solution {
public int romanToInt(String s) {
int sum = 0;
int preNum = getValue(s.charAt(0));
for(int i = 1;i < s.length(); i ++) {
int num = getValue(s.charAt(i));
if(preNum < num) {
sum -= preNum;
} else {
sum += preNum;
}
preNum = num;
}
sum += preNum;
return sum;
}

private int getValue(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;
default: return 0;
}
}
}

    public int romanToInt(String s) {
Map<String, Integer> map = new HashMap<>();
map.put("I", 1);
map.put("IV", 4);
map.put("V", 5);
map.put("IX", 9);
map.put("X", 10);
map.put("XL", 40);
map.put("L", 50);
map.put("XC", 90);
map.put("C", 100);
map.put("CD", 400);
map.put("D", 500);
map.put("CM", 900);
map.put("M", 1000);

int ans = 0;
for(int i = 0;i < s.length();) {
if(i + 1 < s.length() && map.containsKey(s.substring(i, i+2))) {
ans += map.get(s.substring(i, i+2));
i += 2;
} else {
ans += map.get(s.substring(i, i+1));
i ++;
}
}
return ans;
}

public class leetcode13 {

static String twoLetterStart = "CXI";
static Map<String,Integer> twoRoman = new HashMap();
static Map<String,Integer> oneRoman = new HashMap();
public static void main(String[] args) {
// TODO Auto-generated method stub
twoRoman.put("CM", 900);
twoRoman.put("CD", 400);
twoRoman.put("XC", 90);
twoRoman.put("XL", 40);
twoRoman.put("IX", 9);
twoRoman.put("IV", 4);

oneRoman.put("M", 1000);
oneRoman.put("D", 500);
oneRoman.put("C", 100);
oneRoman.put("L", 50);
oneRoman.put("X", 10);
oneRoman.put("V", 5);
oneRoman.put("I", 1);

Scanner in = new Scanner(System.in);
while(in.hasNext()){
String str = in.nextLine();
int result = romainToInt(str);
System.out.println(result);
}
}

public static int romainToInt(String s){
int sum =0;
StringBuilder sb = new StringBuilder(s);
for(int i=0;i<s.length();i++){
char letter = s.charAt(i);
if(twoLetterStart.indexOf(letter)>=0&&i!=(s.length()-1)){
String tmp = sb.substring(i, i+2);
if(twoRoman.containsKey(tmp)){
sum += twoRoman.get(tmp);
i++;
continue;
}
}

sum += oneRoman.get(String.valueOf(letter));
}
return sum;
}

}

posted @ 2021-01-25 23:20  Vincent-yuan  阅读(55)  评论(0编辑  收藏  举报