---
# System prepended metadata

title: Leetcode 13. Roman to Integer
tags: [Math]

---

# Leetcode 13. Roman to Integer
# 字串中找尋子字串 .indexOf()
# 將字串轉成char陣列 .toCharArray()

faster than 82.91%
 runtime : 4ms
 ``` java=
class Solution {    
    public int romanToInt(String s) {
        int result=0;
        for(char ch:s.toCharArray()){
            result+=turnIntoNumber(ch);
        }
        
        if(s.indexOf("IV")!=-1)
            result-=2;
        if(s.indexOf("IX")!=-1)
            result-=2;
        if(s.indexOf("XL")!=-1)
            result-=20;
        if(s.indexOf("XC")!=-1)
            result-=20;
        if(s.indexOf("CD")!=-1)
            result-=200;
        if(s.indexOf("CM")!=-1)
            result-=200;
        
        return result;    
    }
    
     public int turnIntoNumber(char c){
        switch(c){
            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;
        }
         return 0;
    }
}
```


---


* **字串中找尋子字串** 
  **indexOf()**
indexOf()返回一个整数值，指出 String 对象内子字符串的开始位置。如果没有找到子字符串，则返回-1

* **for( : )** 陣列專用的for迴圈
* **.toCharArray()** 將字串轉換成char陣列
``` java=
 String s;
 // 用char ch 存取字串s轉成的陣列
 for(char ch : s.toCharArray()){
 
 } 
 ```















字串中找尋子字串
>https://blog.xuite.net/x_3kkk/java/11380206-%E6%90%9C%E5%B0%8B%E5%AD%97%E4%B8%B2+(+indexOf+%2F+lastIndexOf+)

for迴圈 (一般常見、陣列專用)
> https://ithelp.ithome.com.tw/articles/10158439

toCharArray() 用法
> https://www.runoob.com/java/java-string-tochararray.html

###### tags: `Math` 