將羅馬字母的字符串轉換爲表明的整數
Roman numerals are usually written largest to smallest from left to right. However, there are six instances where subtraction is used:
I can be placed before V (5) and X (10) to make 4 and 9.
X can be placed before L (50) and C (100) to make 40 and 90.
C can be placed before D (500) and M (1000) to make 400 and 900.
Symbol Value I 1 V 5 X 10 L 50 C 100 D 500 M 1000
這題不難,用一個HashMap存羅馬數字和具體數字的對應關係,而後遍歷先後兩兩比較,該加加,該減減指針
public static int romanToInt(String s) { int num = 0; int n = s.length(); for (int i = 0; i < n-1; i++) { int curr = map(s.charAt(i)); //這裏map是本身寫的一個方法,裏面用一個switch,至關於HashMap存對應 int next = map(s.charAt(i+1)); num = curr < next ? num - curr : num + curr; //當時一直想着用一個temp來存減的值,因此無法用for就用了while&point指針,但其實就是很簡單的比後面小的話在總值裏面減去就能夠,不須要temp } num += map(s.charAt(n-1)); return num; }