Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
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; } }
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; }
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; } };
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
LeetCode 13 Roman to Integer (C,C++,Java,Python)
原文地址:http://blog.csdn.net/runningtortoises/article/details/45582383