题目:
Roman numerals
Problem Description
Now let’s think about roman numerals!
- | The Roman numerals for 1 through 10 are I, II, III, IV, V, VI, VII, VIII, IX, and X. |
- | The Roman numerals for 20, 30, 40, and 50 are XX, XXX, XL, and L. |
- | The Roman numeral for any other two-digit number less than 50 can be constructed by concatenating the numeral for its tens and the numeral for its ones. For example, 47 is 40 + 7 = "XL" + "VII" = "XLVII". |
Now given a Roman numeral n (n <= 50), please output the value of the number.
Input
The first line of the input is an integer t, which is the numbers of the test cases.
For each test case, there is one line which is a roman numeral whose value is less or equal to 50.
Output
For each test case you should output the value of the roman numeral.
Sample Input
2
I
II
Sample Output
1
2
对于这个题,简单地来说,就是一个对字符串地处理。罗马数字对应的字符,我们的任务是把它代表的数字表示出来。我一开始的思路是打表,因为我看到n<=50这个条件,但是,由于类似于"XXI"这样的罗马数字不是一个字符,我就放弃了打一个大表的想法。那么就说接下来我的处理,我认为当时我做题时主要困扰我的是两个数字,4和9,也就是"IV"和"IX”,因为别的都可以这样处理,检测到"X”那么+10,但是"IV”和"IX”不行。所以就找规律,容易得到,如果检测到第i位是"I",继续检测第i+1位,如果第i+1位是"V",那么此时,第i位对应的阿拉伯数字不应该+1,而是应该-1,这样,得到的就是4而不是6了(好像没说清楚......)
嗯,还是用代码说话:
if (a[i]=='I')
{
if (a[i+1]=='V') {op[j]=op[j]-1;}
else if (a[i+1]=='X'){ op[j]=op[j]-1; }
else if ((a[i+1]!='X') && (a[i+1]!='V')) op[j]=op[j]+1;
嗯,大概就是这个意思。最后成功AC。整体代码如下:
#include <stdio.h>
#include <string.h>
int n,i,l,j;
char c;
char a[50];
int op[50]={0};
int main()
{
scanf("%d",&n);
c=getchar();
for (j=0;j<n;j++)
{
gets(a);
l=strlen(a);
for (i=0;i<=l;i++)
{
if (a[i]=='V') op[j]=op[j]+5;
if (a[i]=='I')
{
if (a[i+1]=='V') {op[j]=op[j]-1;}
else if (a[i+1]=='X'){ op[j]=op[j]-1; }
else if ((a[i+1]!='X') && (a[i+1]!='V')) op[j]=op[j]+1;
}
if (a[i]=='X') {if (a[i+1]=='L') op[j]=op[j]-10; else op[j]=op[j]+10;}
//if (a[i]=='V') op[j]=op[j]+5;
else if (a[i]=='L') op[j]=op[j]+50;
}
memset(a,0,l);
}
for (j=0;j<n;j++) printf("%d\n",op[j]);
return 0;
//system("pause");
}
//不会写解题报告啊......................写的好烂的赶脚.................