美文网首页
13. Roman to Integer

13. Roman to Integer

作者: hyhchaos | 来源:发表于2016-11-29 14:19 被阅读8次

    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;
    };
    

    优解

    思路差不多

    相关文章

      网友评论

          本文标题:13. Roman to Integer

          本文链接:https://www.haomeiwen.com/subject/qgwapttx.html