13. Roman to Integer

Posted tobeabetterpig

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了13. Roman to Integer相关的知识,希望对你有一定的参考价值。

13. Roman to Integer


class Solution {
    public int romanToInt(String s) {
        if(s == null || s.length() == 0) return 0;
        int result = 0;
        // becauase later when we see the CM, so treat it as MC
        // later when we see CD. we treat it as DC
        // later when we see XC. we treat it as CX, 
        // later when we see XL. we treat it as LX, XL = 90, LX = 110, the diff is 20
        // later when we see IX. we treat it as XI, IX is 9, XI is 11, the diff is 2  
        // later when we see IV. we treat it as VI, VI = 6 , IV = 4, the diff is 2 
        // if we can find those substring at the string s, then we know later 
        // we are gonna add them , but with the opposite order, for example
        // we are gonna add the value of VI, instead of the value of IV. so
        // we substract the difference beforehand 
        if(s.indexOf("CM") != -1) result = result - 200;
        if(s.indexOf("CD") != -1) result = result - 200;
        if(s.indexOf("XC") != -1) result = result - 20;
        if(s.indexOf("XL") != -1) result = result - 20;
        if(s.indexOf("IX") != -1) result = result - 2;
        if(s.indexOf("IV") != -1) result = result - 2;
        
        for(char c : s.toCharArray()){
            if(c == ‘M‘) result += 1000;
            else if(c == ‘D‘) result += 500;
            else if(c == ‘C‘) result += 100;
            else if(c == ‘L‘) result += 50;
            else if(c == ‘X‘) result += 10;
            else if(c == ‘V‘) result += 5;
            else if(c == ‘I‘) result += 1;
        }
        return result;
    
    }
}

 

以上是关于13. Roman to Integer的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 13. Roman to Integer

13. Roman to Integer

#Leetcode# 13. Roman to Integer

java 13. Roman to Integer(#)。java

java 13. Roman to Integer(#)。java

java 13. Roman to Integer(#)。java