c++ - 为什么 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++
并且++i
做i + 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'
是true
butstr[++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') { ... }
...
推荐阅读
- php - PHPMailer semi issue
- sql - 如何通过连接 2 个临时表创建永久表
- algorithm - 寻路任务 - 如何在从 A 到 B 的最短路径上比 O ( n ) 更快地找到下一个顶点?
- objective-c - Objective C adding methods to classes argument mismatch
- ajax - 从视图到控制器的 IEnumerable 模型为 NULL
- jenkins-pipeline - 在声明性詹金斯管道中引用变量
- c++ - PostgreSQL-9.1 观察模式变化
- json - JSON - ISuperObject
- python - Pandas - 具有重复值的列的外部连接
- python - 按比例将 NaN 替换为现有值