Problem:
Given a Roman numeral, convert it to an integer.
Input is guaranteed to being within the range from 1 to 3999.
Solution: Time complexity O (n) topic: In contrast to 12, give a Roman numeral, ask to convert to decimal number problem solving idea:
Java source code (spents 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 Language Source code (spents 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 + + source code (spents 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 source code (spents 138ms):
Class solution: # @param {string} s # @return {integer} def romantoint (self, s): index=0;num=0;temp=0< C4/>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 elif c== ' C ': num+ =80 if temp==10 else 100;temp=100 elif c== ' D ': num+=300 if temp==100 else elif c== ' M ': num+=800 if temp==100 E LSE return NUM
Leetcode Roman to Integer (C,c++,java,python)