罗马数字转换整数
Given a number in Roman format and we have to convert it into integer/decimal format.
给定罗马格式的数字,我们必须将其转换为整数/十进制格式。
Example:
例:
Input: XIV Output: 14 Input: XI Output: 11
Algorithm:
roman_to_int(string roman)
roman_to_int(罗马字符串)
Step 1: Declare all Roman characters and its integer value in a Array ( rmaplgdqc ) where Index=’Roman_character’Step 2: If (Length of roman) =<1 Return corresponding Array index value.Step 3: elseStep 4: Repeat step 5 and step 6, While((i<roman.size()) Step 5: if(rmap[roman[i]]<rmap[roman[i+1]]) number+=rmap[roman[i+1]]-rmap[roman[i]] //number is storing the integer number //after conversion; number=0 i+=2;Step 6: else number+=rmap[roman[i]] i++Step 7:return number
Program:
#include <bits/stdc++.h>using namespace std;int roman_to_int(string roman){map<char,int> rmap;rmap['I'] = 1;rmap['V'] = 5;rmap['X'] = 10;rmap['L'] = 50;rmap['C'] = 100;rmap['D'] = 500;rmap['M'] =1000;int number=0,i=0;//If input is only one characterif(roman.length()<=1){return rmap[roman.at(0)];}else{while(i<roman.size()){if(rmap[roman[i]]<rmap[roman[i+1]]){number+=rmap[roman[i+1]]-rmap[roman[i]];i+=2;}else{number+=rmap[roman[i]];i++;}}return number;}}int main(){string roman;cout<<"Enter the roman number (in capital only): ";getline(cin,roman);int number;number=roman_to_int(roman);cout<<"The interger form is: "<<number;return 0;} .minHeight{ min-height: 250px; } @media (min-width: 1025px){ .minHeight{ min-height: 90px; } } .minHeight{ min-height: 250px; } @media (min-width: 1025px){ .minHeight{ min-height: 90px; } } Output
Enter the roman number (in capital only): XIVThe interger form is: 14 Explanation:
Sample Input : XIV=> String lenght is >1, so it is "else" part of roman_to_int() will execute here.Step1: i=0, so, 0<3 (size of string), while loop will execute.Now, rmap[roman[0]]=rmap[X] that is equal to 10, and rmap[roman[1]]=1,So, 10<1 that is false, so "else" part inside the while loop will execute and number+=rmap[roman[i]];=> number=0+10=>number=10 and i=0+1 that is i=1Step2:i=1, so, 1<3, again while loop will execute.Now, rmap[roman[1]]=rmap[I] that is eaual to 1 and rmap[roman[2]]=5,So, 1<5, that is true... So, if part inside the while loop will execute andnumber+=rmap[roman[i+1]]-rmap[roman[i]];=>number+=rmap[V]-rmap[I]=>number+=5-1=>number+=4=>number=10+4=>number=14And, i=i+2 that is i=3Step3:i=3, so, 3<3 that is false.So, return value will be 14. 翻译自: https://www.includehelp.com/cpp-programs/convert-roman-number-to-integer-number.aspx
罗马数字转换整数