LeetCode 13 Roman to Integer (C,C++,Java,Python)
Problem:
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
Solution:
题目大意:
解题思路:
Java源代码(用时749ms):
public class Solution { public int romanToInt(String s) { int index=0,num=0,temp=0; while(index<s.length()){ char c=s.charAt(index++); switch(c){ case 'I':num+=1;temp=1;break; case 'V':num+=temp==1?3:5;break; case 'X':num+=temp==1?8:10;temp=10;break; case 'L':num+=temp==10?30:50;break; case 'C':num+=temp==10?80:100;temp=100;break; case 'D':num+=temp==100?300:500;break; case 'M':num+=temp==100?800:1000;break; } } return num; } }
C语言源代码(用时18ms):
int romanToInt(char* s) { int num=0,temp=0; while(*s){ switch(*s){ case 'I':num+=1;temp=1;break; case 'V':num+=temp==1?3:5;break; case 'X':num+=temp==1?8:10;temp=10;break; case 'L':num+=temp==10?30:50;break; case 'C':num+=temp==10?80:100;temp=100;break; case 'D':num+=temp==100?300:500;break; case 'M':num+=temp==100?800:1000;break; } s++; } return num; }
C++源代码(用时58ms):
class Solution { public: int romanToInt(string s) { int index=0,num=0,temp=0; while(index<s.size()){ char c=s[index++]; switch(c){ case 'I':num+=1;temp=1;break; case 'V':num+=temp==1?3:5;break; case 'X':num+=temp==1?8:10;temp=10;break; case 'L':num+=temp==10?30:50;break; case 'C':num+=temp==10?80:100;temp=100;break; case 'D':num+=temp==100?300:500;break; case 'M':num+=temp==100?800:1000;break; } } return num; } };
Python源代码(用时138ms):
class Solution: # @param {string} s # @return {integer} def romanToInt(self, s): index=0;num=0;temp=0 while index<len(s): c = s[index];index+=1 if c=='I':num+=1;temp=1 elif c=='V':num+=3 if temp==1 else 5 elif c=='X':num+=8 if temp==1 else 10;temp=10 elif c=='L':num+=30 if temp==10 else 50 elif c=='C':num+=80 if temp==10 else 100;temp=100 elif c=='D':num+=300 if temp==100 else 500 elif c=='M':num+=800 if temp==100 else 1000 return num
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。