24 ms C solution (beats 53.68%)


  • 0
    int romanToInt(char* s) {
        int sum = 0;
        int curr = 0, pre = 0;
    
        while(*s != '\0'){
            switch(*s){
                case 'I': curr = 1; break;
                case 'V': curr = 5; break;
                case 'X': curr = 10; break;
                case 'L': curr = 50; break;
                case 'C': curr = 100; break;
                case 'D': curr = 500; break;
                case 'M': curr = 1000; break;
            }   
            sum += curr;
            if(pre < curr){
                sum -= (pre<<1);  // sum = sum - pre * 2 ; For example IV = I + V - I * 2;
            }
            pre = curr;
            s++;
        }
        return sum;
    }

Log in to reply
 

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