【LeetCode】013.Roman Integer

来源:互联网 发布:单片机协议栈开发 编辑:程序博客网 时间:2024/06/10 08:27

题目如下:

Given a roman numeral, convert it to an integer.

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

解答:

仔细观察罗马数字,只有出现IV(4),IX(9),XL(40),XC(90)等时,才需要减去左边字母代表的值,其余情况则直接加即可。

所以,从左到右遍历即可,用一个变量记录上一个字符串,进行减操作;


代码如下:

public class Solution {    public int romanToInt(String s) {char[] ac = s.toCharArray();int result = 0;char lastChar = 0;for(int i=0;i<ac.length;i++){switch(ac[i]){case  'M':if(lastChar == 'C'){ //CMresult -= 100;result += 900;lastChar = ac[i];} else{result += 1000;lastChar = ac[i];} break;case  'D':if(lastChar == 'C'){ // CDresult -= 100;result += 400;lastChar = 0;} else {result += 500;lastChar = ac[i];}break;case 'C':if(lastChar == 'X'){ // XCresult -= 10;result += 90;lastChar = 0;} else {result += 100;lastChar = ac[i];}break;case 'L':if(lastChar == 'X'){ // XLresult -= 10;result += 40;lastChar = 0;} else {result += 50;lastChar = 0;}break;case 'X' : if(lastChar == 'I'){ // IXresult -= 1;result += 9;lastChar = 0;} else {result += 10;lastChar = ac[i];}break;case 'V' :if(lastChar == 'I'){ // IVresult -= 1;result += 4;lastChar = 0;} else {result += 5;lastChar = ac[i];}break;case 'I' :result += 1;lastChar = ac[i];break;default :return 0;}}return result;}}



0 0
原创粉丝点击