1. 程式人生 > >leetcode-13羅馬字元轉整數

leetcode-13羅馬字元轉整數

leetcode-13羅馬字元轉整數

  演算法:轉換的規律是先逐字元按照對應的阿拉伯數字累加,然後對於特殊的(I、X、C出現在左側)要處理。處理方法:出現特殊字元組合減去雙倍的左側字元(在開始的處理中已經加過一次,而實際的結果中卻是要減去,那麼就需要在加的基礎上減去兩倍)。

Code:

vertion : Java

 1 class Solution {
 2     public int romanToInt(String s) {
 3         int ans = 0;
 4         //處理特定字元
 5         if(s.indexOf("IV") != -1)
6 { 7 ans += -2; 8 } 9 if(s.indexOf("IX") != -1) 10 { 11 ans += -2; 12 } 13 if(s.indexOf("XL") != -1) 14 { 15 ans += -20; 16 } 17 if(s.indexOf("XC") != -1) 18 { 19 ans += -20;
20 } 21 if(s.indexOf("CD") != -1) 22 { 23 ans += -200; 24 } 25 if(s.indexOf("CM") != -1) 26 { 27 ans += -200; 28 } 29 30 //逐字元處理 31 for(int i=0; i<s.length(); i++) 32 { 33 char c = s.charAt(i);
34 switch(c) 35 { 36 case 'I': 37 ans += 1; 38 break; 39 case 'V': 40 ans += 5; 41 break; 42 case 'X': 43 ans += 10; 44 break; 45 case 'L': 46 ans += 50; 47 break; 48 case 'C': 49 ans += 100; 50 break; 51 case 'D': 52 ans += 500; 53 break; 54 case 'M': 55 ans += 1000; 56 break; 57 } 58 } 59 return ans; 60 } 61 }