为什么 if/else if 方法对 Roman To integer 转换问题给出错误答案?这是来自leetcode的问题

这是我所指的问题:https :
//leetcode.com/problems/roman-to-integer/

这是我用于以下操作的代码:

int romanToDecimal(string &str) {
     int num=0; 
    for(int i=0; i<str.size(); i++){
        //three special cases given
        if(str[i]=='I' and str[i++]=='V'){
          num=num+4; 
            str.substr(i+2);
        }
       else if(str[i]=='I' and str[i++]=='X'){
            num=num+9;
            str.substr(i+2);
        }
        else if(str[i]=='X' and str[i++]=='L'){
            num=num+40;
            str.substr(i+2);
        }
        else if(str[i]=='X' and str[i++]=='C'){
            num=num+90;
            str.substr(i+2);
        }
        else if(str[i]=='C' and str[i++]=='D'){
            num=num+400;
            str.substr(i+2);
        }
        else if(str[i]=='C' and str[i++]=='M'){
            num=num+900;
            str.substr(i+2);
        }
        else if(str[i]=='I'){
            num=num+1;
        }
        else if(str[i]=='V'){
            num=num+5;
        }
        else if(str[i]=='X'){
            num=num+10;
        }
        else if(str[i]=='L'){
            num=num+50;
        }
        else if(str[i]=='C'){
            num=num+100;
        }
        else if(str[i]=='D'){
            num=num+500;
        }
        else if(str[i]=='M'){
            num=num+1000;
        }
        
    }
    return num;
}

它总是最终给出错误的答案,而不是迭代和进一步添加数字。为什么?

回答

i++++ii + 1做了三件不同的事情。

并且因为i++工作原理,str[i]=='I' and str[i++]=='V'实际上相当于str[i]=='I' and str[i]=='V',始终是false

And i++(or ++i) 在这里完全错误,您需要i + 1然后在if. 与substr不需要的调用一样,并且无论如何都会返回子字符串,因此它实际上并没有做任何有用的事情。

例如:

if(str[i] == 'I' and str[i + 1] == 'V') {
num=num + 4;
++i;
}

至于为什么i++(和++i)在条件本身内部是错误的,想想条件str[i]=='I'是否是truestr[++i]=='V'为假......然后你会i在检查下一个条件之前增加:

// Begins with i == 0
if(str[i]=='I' and str[++i]=='V') { ... }
// If the above condition is false, this will be checked
// BUT! Here i might be equal to 1 because of the above increment
else if(str[i]=='I' and str[++i]=='X') { ... }
...

以上是为什么 if/else if 方法对 Roman To integer 转换问题给出错误答案?这是来自leetcode的问题的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>