1. 程式人生 > 實用技巧 >Codeforces Round #688 (Div. 2) D

Codeforces Round #688 (Div. 2) D

13.羅馬數字轉整數class Solution { public int romanToInt(String s) {

int size = s.length();
        int[] nums = new int[size];
        //char ch = s.charAt(4);
        for(int i =0;i<s.length();i++){
            char ch = s.charAt(i);
            ch = s.charAt(i);
            switch (ch){
                
case 'I': nums[i] = 1; break; case 'V': nums[i] = 5; break; case 'X': nums[i] = 10; break; case 'L': nums[i] = 50;
break; case 'C': nums[i] = 100; break; case 'D': nums[i] = 500; break; case 'M': nums[i] = 1000; break; } } //Vector vector = new Vector();
int sum = 0; for(int i = 0;i<size;i++){ if(i+1<size&&nums[i]<nums[i+1]) { int m =1; for (int j = 0; j < (int) Math.log10(nums[i]); j++) {//log可以用來確定量級 m *= 10; } if((m/nums[i]) == 1){ //vector.add(nums[i+1] - nums[i]); sum = sum + nums[i+1] - nums[i]; i = i+1; } }else{ //vector.add(nums[i]); sum = sum +nums[i]; } } return sum; } //System.out.println(vector); }

知識點:
1.字串操作
s.length() //字串的長度大小

s.charAt(i) //取出字串中的一位字元

2.容器操作
Vector vector = new Vector(); //定義一個容器物件
System.out.println(vector);    //輸出容器,這裡和C++不一樣,不能輸出像vector[i]這種

vector.add(nums[i]); //在末尾加值,如果不是末尾就這樣:
vector.add(2,nums[i]);和C++不太一樣