本文主要是介绍LeetCode13 Roman to Integer,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目要求
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
Subscribe to see which companies asked this question
package com.syy.leetcode13;public class solution {public int romanToInt(String s) {int sum = 0;//建立对应的函数与数字的对照关系int[] arr = new int[s.length()];for(int i = s.length() - 1; i >= 0; i--) {int temp = 0;switch(s.charAt(i)) {case 'I' :temp = 1;break;case 'V' :temp = 5;break;case 'X' :temp = 10;break;case 'L' :temp = 50;break;case 'C' :temp = 100;break;case 'D' :temp = 500;break;case 'M' :temp = 1000;break;}arr[i] = temp;}//拆分字符串if(arr.length == 1) {return arr[0];}sum = arr[arr.length - 1];for(int i = arr.length - 2; i >= 0 ; i--) {int temp = arr[i] >= arr[i + 1] ? arr[i] : -arr[i];sum += temp;}return sum;}
}
这篇关于LeetCode13 Roman to Integer的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!