LeetCode 13 Roman to Integer (C,C++,Java,Python)

来源:互联网 发布:Linux下ifconfig 编辑:程序博客网 时间:2024/06/06 12:40

Problem:

Given a roman numeral, convert it to an integer.

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

Solution:

时间复杂度O(n)

题目大意:

与12题相反,给一个罗马数字,要求转化为十进制数字

解题思路:


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


0 0