LeetCode 13. Roman to Integer
Posted hzg1981
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 13. Roman to Integer相关的知识,希望对你有一定的参考价值。
first:
class Solution { public int romanToInt(String s) { char[] charArray = s.toCharArray(); int result =0; for(int i=0;i<charArray.length;i++){ if(charArray[i]==‘I‘&&(charArray[i+1]==‘V‘||charArray[i+1]==‘X‘)){ result--; }else if(charArray[i]==‘X‘&&(charArray[i+1]==‘L‘||charArray[i+1]==‘C‘)){ result -=10; }else if(charArray[i]==‘C‘&&(charArray[i+1]==‘D‘||charArray[i+1]==‘M‘)){ result -=100; }else{ switch (charArray[i]){ case ‘I‘:result++; break; case ‘V‘:result+=5; break; case ‘X‘:result+=10; break; case ‘L‘:result+=50; break; case ‘C‘:result+=100; break; case ‘D‘:result+=500; break; case ‘M‘:result+=1000; } } } return result; } }
result:
Run Code Status: Runtime Error Run Code Result: Your input "III" Your answer Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3 at Solution.romanToInt(Solution.java:6) at __DriverSolution__.__helper__(__Driver__.java:8) at __Driver__.main(__Driver__.java:52)
second:
class Solution { public int romanToInt(String s) { char[] charArray = s.toCharArray(); int result =0; for(int i=0;i<charArray.length;i++){ if(charArray[i]==‘I‘&&i+1<charArray.length&&(charArray[i+1]==‘V‘||charArray[i+1]==‘X‘)){ result--; }else if(charArray[i]==‘X‘&&i+1<charArray.length&&(charArray[i+1]==‘L‘||charArray[i+1]==‘C‘)){ result -=10; }else if(charArray[i]==‘C‘&&i+1<charArray.length&&(charArray[i+1]==‘D‘||charArray[i+1]==‘M‘)){ result -=100; }else{ switch (charArray[i]){ case ‘I‘:result++; break; case ‘V‘:result+=5; break; case ‘X‘:result+=10; break; case ‘L‘:result+=50; break; case ‘C‘:result+=100; break; case ‘D‘:result+=500; break; case ‘M‘:result+=1000; } } } return result; } }
result:
conclusion:
以上是关于LeetCode 13. Roman to Integer的主要内容,如果未能解决你的问题,请参考以下文章
Leetcode 13. Roman to Integer(python)
[LeetCode][13]Roman to Integer解析 罗马字符转int类型关于栈的常数实现-Java实现
[LeetCode][13]Roman to Integer解析 罗马字符转int类型关于栈的常数实现-Java实现