12ms accepted C solution


  • 0
    P

    int romanToInt(char* s) {

    int map[26];
    
    memset(map, 0, 26);
    
    map['I'-65]=1;
    map['V'-65]=5;
    map['X'-65]=10;
    map['L'-65]=50;
    map['C'-65]=100;
    map['D'-65]=500;
    map['M'-65]=1000;
    
    int len=strlen(s), i, sum=0, prev, cur=map[s[0]-65];
    
    for(i=1; i<len; i++)
    {
        prev=map[s[i-1]-65];
        cur=map[s[i]-65];
        
        if(prev>=cur)
        {
            sum+=prev;
        }
        else
        {
            sum+=cur-prev;
            if(i==(len-1))
            	cur=0;/*to avoid adding up last Roman Number in case of for e.g XIV. We would have already added 10+4. We needn't add 5 again in return sum+cur. Thus making cur=0*/
            else
            	cur=map[s[i+1]-65];/*In case we have XCV, and cur='C'. We have already added 90. we would want cur to be 'V' after for loop ends. else cur will retain 'C'. Then we would return 90+100 instead of 90+5*/
            i++;
        }
        
    }
    if(sum==0)
    return cur;
    else
    return sum+cur;/*to add the last Roman Number*/
    

    }


  • -1
    Z

    Something was unnecessary, so I Changed it. Also Accepted.

    int map[26];
    
    memset(map, 0, 26);
    
    map['I']=1;
    map['V']=5;
    map['X']=10;
    map['L']=50;
    map['C']=100;
    map['D']=500;
    map['M']=1000;
    
    int len=strlen(s), i, sum=0, prev, cur=map[s[0]];
    
    for(i=1; i<len; i++)
    {
        prev=map[s[i-1]];
        cur=map[s[i]];
    
        if(prev>=cur)
        {
            sum+=prev;
        }
        else
        {
            sum+=cur-prev;
            if(i==(len-1))
                cur=0;
            else
                cur=map[s[i+1]];
            i++;
        }
    
    }
    return sum+cur;
    

  • 0
    P

    Checked it. It works. But I didn't understand how is map['I'] for example assigning map[8] to 1. Won't map['I'] be map[73] ?


  • 0
    C

    I changed map['I'] to map[73], it also works. I think this array indexing exceed allocated memory in function stack frame. It's very dangerous and must be forbidden!


  • 0
    C

    int len=strlen(s), i, sum=0, prev, cur=map[s[0]];
    // I think cur=map[s[0]] is useless, because in for-loop, cur will be re-assigned to map[s[0]] in first cycle

    // oops...I forgot len=1 condidtion, you are right!


  • 0
    P

    yes, you got it. cur=map[s[0]] is used to take care of when len=1.
    I think it is not safe to assign a value to map[73] and so on, when we have declared map as:
    int map[26]


Log in to reply
 

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