1. 程式人生 > >LeetCode之Easy篇 ——(13)Roman to Integer

LeetCode之Easy篇 ——(13)Roman to Integer

i++ tco bre from input bsp roman 通過 數字

Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

思路分析:

  1、熟悉羅馬數字的規則。見LeetCode之Easy篇 ——(12)Integer to Roman

  2、將輸入的羅馬數字轉化成數組,並逐一通過case比對,然後根據其規則進行運算。

Java代碼示例:

class Solution {
    public int romanToInt(String s) {
        char[] letters = s.toCharArray();
		int[] nums = new int[letters.length];
		int answer=0;
		
		for(int i = 0; i<letters.length; i++){
			switch(letters[i]){
				case ‘M‘: nums[i]=1000;break;
				case ‘D‘: nums[i]=500;break;
				case ‘C‘: nums[i]=100;break;
				case ‘L‘: nums[i]=50;break;
				case ‘X‘: nums[i]=10;break;
				case ‘V‘: nums[i]=5;break;
				case ‘I‘: nums[i]=1;break;
			}
		}
		
		for(int i=0; i<nums.length-1;i++){
			if(nums[i]>=nums[i+1]) answer+=nums[i];
			else answer-=nums[i];
		}
		answer+=nums[nums.length-1];
		return answer;
    }
}

LeetCode之Easy篇 ——(13)Roman to Integer