My 44ms AC Solution


  • 0
    M
    class Solution {
    	int getTranslateNum(char s) {
    		switch(s) {
    		case 'I': return 1;
    		case 'V': return 5;
    		case 'X': return 10;
    		case 'L': return 50;
    		case 'C': return 100;
    		case 'D': return 500;
    		case 'M': return 1000;
    		default: return 0;
    		}
    		return 0;
    	}
    
    public:
    	int romanToInt(string s) {
    		int index=0;
    		int base=0;
    		int temp=0;
    		int len=s.length();
    
    
    		do{
    			if(index+1 == len){
    				base -= temp;
    				break;
    			}
    			if(getTranslateNum(s[index]) >= getTranslateNum(s[index+1]))
    			{
    				base += getTranslateNum(s[index]) - temp;
    				temp =0;
    			}
    			else
    				temp += getTranslateNum(s[index]);
    
    			index++;
    		}
    		while (index < len);
    
    		return (base + getTranslateNum(s[s.length()-1])) < 4000 ? base + getTranslateNum(s[s.length()-1]) : 0;
    	}
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.