码迷,mamicode.com
首页 > 其他好文 > 详细

13. Roman to Integer

时间:2018-08-28 21:18:59      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:color   dex   val   bst   hose   har   with   ||   man   

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

标签:color   dex   val   bst   hose   har   with   ||   man   

原文地址:https://www.cnblogs.com/tobeabetterpig/p/9550677.html

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