13. Roman to Integer

2016-11-29  本文已影响8人  hyhchaos

Java

public class Solution {
    public int romanToInt(String s) {
        int sum=0;
        int trans[]=new int[200];
        trans['I']=1;
        trans['V']=5;
        trans['X']=10;
        trans['L']=50;
        trans['C']=100;
        trans['D']=500;
        trans['M']=1000;
        sum=trans[s.charAt(0)];
        for(int i=0;i<s.length()-1;i++)
        {
            if(trans[s.charAt(i)]>=trans[s.charAt(i+1)])
            sum+=trans[s.charAt(i+1)];
            else
            sum=sum+trans[s.charAt(i+1)]-2*trans[s.charAt(i)];
        }
        return sum;
    }
}

Javascript

/**
 * @param {string} s
 * @return {number}
 */
var romanToInt = function(s) {
        var sum=0;
        var trans=[];
        trans['I']=1;
        trans['V']=5;
        trans['X']=10;
        trans['L']=50;
        trans['C']=100;
        trans['D']=500;
        trans['M']=1000;
        sum=trans[s.charAt(0)];
        for(var i=0;i<s.length-1;i++)
        {
            if(trans[s[i]]>=trans[s[i+1]])
            sum+=trans[s[i+1]];
            else
            sum=sum+trans[s[i+1]]-2*trans[s[i]];
        }
        return sum;
};

优解

思路差不多

上一篇下一篇

猜你喜欢

热点阅读