首页 > 解决方案 > 为什么 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;
}

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

标签: c++roman-numerals

解决方案


i++并且++ii + 1三件不同的事情。

并且因为如何i++工作,str[i]=='I' and str[i++]=='V'实际上将等同于str[i]=='I' and str[i]=='V',它总是false

i++(或++i)在这里是完全错误的,你需要i + 1然后在if. 就像substr不需要调用的那样,它无论如何都会返回子字符串,所以它实际上并没有做任何有用的事情。

例如:

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

至于为什么i++(and ++i) 在条件本身内部是错误的,想一想条件str[i]=='I'truebutstr[++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') { ... }
...

推荐阅读