C++ for-loop to translate Rom to Int and summation.


  • 0
    X
    class Solution {
    public:
        int romanToInt(string s) {
            if(s.length() < 1) return 0; 
            if(s.length() == 1)return rtoi(s[0]); 
    /*==========================================================================
        Roman:	I	V	X	L	C	D	M
        Int:	1	5	10	50	100	500	1000
        V 1.0 : get nums right to left, see right > left ? r-l : r+l; 
        Time: O(n),  space:O(1)
    *///========================================================================
            int lo = 0, hi = 0, sum = 0; 
            for(int i = s.length()-1; i >= 0; i--){
                lo = rtoi(s[i]);
                if(i-1 >= 0) hi = rtoi(s[i-1]);
                else         hi = 0; // no more num.
                
                if(hi < lo) sum += (lo - 2*hi); // -2*hi bcz next loop will add it back.
                else        sum += lo; 
            }
            return sum; 
        }
    private: 
        inline int rtoi(char r){ // rom to int.
            switch(r){
                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; 
            }
        }
    };
    

Log in to reply
 

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