Simple algorithm problem 6--roman numerals into integers
This algorithm is written in C + +
This algorithm question is from the garlic guest
This topic is suitable for beginners algorithm or want to understand programming, but only a little bit of grammar people ... Topic
Given a Roman numeral s, converts Roman numerals to integers.
such as the Roman numeral i,ii,iii,iv,v respectively represent the numbers 1, 2, 3, 4, 5.
First of all, to understand the Roman numeral notation, there are 7 basic characters: I, V, X, L, C, D, M, respectively, 1, 5, 10, 50, 100, 500, 1000. rules
In the form of numbers, there are the following rules:
1, the same number of ligatures, the number represented is equal to the number of these numbers, such as: III = 3;
2, the small number in the large number of the right, the number represented equal to the number of these numbers, such as: VIII = 8;XII = 12;
3, small number, (limited to Ⅰ, X and C) on the left of large numbers, the number represented is equal to the number of reduced number of large numbers, such as: IV = 4;ix = 9;
4, normal use, the number of ligatures should not repeat more than three times. Input Format
Enter a Roman numeric string that corresponds to the number s (1≤s≤3999). output Format
The output corresponds to the integer s.
shaped like:
input
Cxxiii
Output
123 Digging up dot
In fact, I think this problem is nothing, learning process-oriented procedures should be learned, when teaching Tan Haoqiang's C, there are many such examples. This problem is suitable for beginners to see.
Other people write blogs are very advanced things, I write very simple, from the most basic start, slowly and gradually. [Helpless to say a word]
#include <iostream> #include <string> using std::string;
using namespace Std;
int Romantoint (string Roman);
int main () {string Roman;
cin>>roman;
Cout<<romantoint (Roman);
return 0;
int Romantoint (string Roman) {int num=0;
for (int i=roman.length () -1;i>-1;i--) {if (Roman.data () [i]== ' I ') {num+=1;
} if (Roman.data () [i]== ' V ') {if (Roman.data () [i-1]== ' I ')
{num=num+5-2;
else {num+=5;
} if (Roman.data () [i]== ' X ') {if (Roman.data () [i-1]== ' I ')
{num=num+10-2;
else {num+=10;
} if (Roman.data () [i]== ' L ') { if (Roman.data () [i-1]== ' X ') {num=num+50-20;
else {num+=50;
} if (Roman.data () [i]== ' C ') {if (Roman.data () [i-1]== ' X ')
{num=num+100-20;
else {num+=100;
} if (Roman.data () [i]== ' D ') {if (Roman.data () [i-1]== ' C ')
{num=num+500-200;
else {num+=500;
} if (Roman.data () [i]== ' M ') {if (Roman.data () [i-1]== ' C ')
{num=num+1000-200;
else {num+=1000; }} return num; }
The test was successful. ~[laughs Cry]