Problem Description: Given A Roman numeral, convert it to an integer.
Input is guaranteed to being within the range from 1 to3999.
Problem Analysis:{' M ', ' D ', ' C ', ' L ', ' X ', ' V ', ' I '}; corresponding to {, 5, 1} respectively;
When there is a similar CM situation, that is, the smaller in front of the larger, then the larger should be subtracted from the smaller, that is, 1000-100=900;
Otherwise, it is added directly;
This is used to store the HashMap , the time complexity ofget () is O (1), and space is used to change the time
Only need to pay attention to the condition judgment and carry case can
Code:
public class Solution {public int romantoint (String s) {if (s = = NULL | | s.length () = = 0) return 0;char[] Numberchars = {' M ' , ' D ', ' C ', ' L ', ' X ', ' V ', ' I '};int[] values = {1000, 500, 100, 50, 10, 5, 1}; Hashmap<character, integer> map = new hashmap<> (); for (int i = 0; i < numberchars.length; i++) {Map.put (Numbe Rchars[i], values[i]);} int result = 0;char[] Datas = S.tochararray (), int i = 1;int last = Map.get (datas[0]), int now = 0;while (i <= datas.lengt h) {if (I <= datas.length-1) {now = Map.get (Datas[i]), if (now > last) {result + = (now-last); ++i;if (I < Datas.leng th) Last = Map.get (Datas[i]);} Else{result + = Last;last = Now;}} Else{result + = Last;last = Now;} ++i;} return result;}}
LEETCODE-13 Roman to Integer