码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2015-05-08 18:15:03      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:c   c++   java   leetcode   python   

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


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

标签:c   c++   java   leetcode   python   

原文地址:http://blog.csdn.net/runningtortoises/article/details/45582383

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!