[英]I need to find the integer value for the given roman number. I can't get the solution
I used my logic, I am confident my logic was correct,but for some reasons my code doesn't work.我使用了我的逻辑,我相信我的逻辑是正确的,但由于某些原因,我的代码不起作用。 I need help to point out what mistake I made, also sorry for declaring my variables as random alphabets without any semantic meaning.
我需要帮助来指出我犯了什么错误,也很抱歉将我的变量声明为没有任何语义意义的随机字母。
#include<iostream>
using namespace std;
int main()
{
char s[15];
cin >> s;
char a[7] = {'I','V','X','L', 'C', 'D', 'M'};
int b[7] = {1,5,10,50,100,500,1000};
int count = 0,i=0,j,k;
while(s[i]!='\0')
{
for(j=0;j<7;j++)
{
int l=0;
if(s[i]==a[j])
{
k = j;
if(s[i+1] == a[j])
{
l = j;
}
}
if(k<l)
{
count = count + (b[l]-b[k]);
i+=2;
}
else
{
count = count + b[k];
i++;
}
}
}
cout << count;
}
This looks like a homework assignment, and while I think you should go back to the drawing board in order to figure this out, maybe a hint would suffice.这看起来像是一项家庭作业,虽然我认为您应该将 go 回到绘图板上以便弄清楚这一点,但也许一个提示就足够了。 When we analyze a roman integer, it has it's most significant 'digits'(letters) closer to the start of it.
当我们分析罗马 integer 时,它的最重要的“数字”(字母)更接近它的开头。 The only exception is when the 'digit' directly to the right of it is of higher order.
唯一的例外是直接在其右侧的“数字”具有更高的顺序。 You may find it easier to solve the problem from the least significant digits forward.
您可能会发现从最低有效数字开始更容易解决问题。 Given this scenario, the procedure I'd follow is this:
鉴于这种情况,我要遵循的程序是这样的:
Number : MCMXCIV
Current Roman Digit | Current Answer int
V | 5 (no matter what the first character is, it will always be the base)
I | 5 - 1 (I is smaller than V, therefore we substract it)
C | 5 - 1 + 100
X | 5 - 1 + 100 - 10 (X is smaller than C, we substract)
M | 5 - 1 + 100 - 10 + 1000
C | 5 - 1 + 100 - 10 + 1000 - 100
M | 5 - 1 + 100 - 10 + 1000 - 100 + 1000 = 1994
The solution:解决方案:
int romanCharToInt(char c) {
switch(c) {
case 'I':
return 1;
case 'V':
return 5;
case 'X':
return 10;
case 'L':
return 50;
case 'C':
return 100;
case 'D':
return 500;
case 'M':
return 1000;
}
return 0;
}
int romanToInt(string s) {
int result = 0;
int stored_sum = 0;
int last_val = -1;
for (char elem : s) {
int val = romanCharToInt(elem);
if (last_val == -1) {
stored_sum += val;
} else if (last_val > val) {
result += stored_sum;
stored_sum = val;
} else if (last_val == val) {
stored_sum += val;
} else {
stored_sum = val - stored_sum;
}
last_val = val;
}
result += stored_sum;
stored_sum = 0;
return result;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.