您的位置:首页 > 其它

1002 Roman numerals

2013-01-30 11:02 351 查看
第一次写解题报告,选了一道目前做过的最简单的题,就当是练手了

1002 Roman numerals:http://acm.bit.edu.cn/mod/programming/view.php?a=488


Roman numerals

时间限制: 1秒 内存限制: 64M

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

无论从看上去还是实际来讲都是比较简单的一道题。

自习观察了一下罗马数字(罗马数字对照表,转自百度文库)的规律就发现原来罗马数字中放在整数前面用来表示减去的数字只有一位

因此便利字符串,将后位大于当前位的数字取相反数,再顺次加和就能得到正确的结果

#include<stdio.h>

#include<string.h>

#define N 10

void init(int n[],char r[])

{

memset(n,0,sizeof(int)*N);

for ( ; *r != '\0'; r ++, n ++ )

{

switch ( *r )

{

case 'I': *n = 1; break;

case 'V': *n = 5; break;

case 'X': *n = 10;break;

case 'L': *n = 50;break;

}

}

return ;

}//此函数用于将每一位的罗马数字翻译成对应的数字,只是翻译不作处理

int main()

{

char r
;

int n
, i, sum, times;

scanf("%d",×);

for ( ; times > 0; times -- )

{

scanf("%s",r);

init(n,r);

for ( i = 0; i <= (int)strlen(r) - 1; i ++ )

if ( n[i+1] > n[i] ) n[i] *= -1;//此循环用于取相反数

for ( sum = 0, i = 0; i <= (int)strlen(r) - 1; i ++ )

sum += n[i];

printf("%d\n",sum);

}

return 0;

}

测试数据:(就是从1~50的所有罗马数字)

50

I

II

III

IV

V

VI

VII

VIII

IX

X

XI

XII

XIII

XIV

XV

XVI

XVII

XVIII

XIX

XX

XXI

XXII

XXIII

XXIV

XXV

XXVI

XXVII

XXVIII

XXIX

XXX

XXXI

XXXII

XXXIII

XXXIV

XXXV

XXXVI

XXXVII

XXXVIII

XXXIX

XL

XLI

XLII

XLIII

XLIV

XLV

XLVI

XLVII

XLVIII

XLIX

L
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: