Roman Number to Integer
PROBLEM :
Given an string in roman no format (s) your task is to convert it to integer .
Input:
The first line of each test case contains the no of test cases T. Then T test cases follow. Each test case contains a string s denoting the roman no.
Output:
For each test case in a new line print the integer representation of roman number s.
Constraints:
1<=T<=100
1<=roman no range<4000
Example:
Input
2
V
III
Output
5
3
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
#include<bits/stdc++.h>
using namespace std;
int value(char r)
{
if (r == 'I')
return 1;
if (r == 'V')
return 5;
if (r == 'X')
return 10;
if (r == 'L')
return 50;
if (r == 'C')
return 100;
if (r == 'D')
return 500;
if (r == 'M')
return 1000;
return 0 ;
}
int Roman2Integer(string str)
{
int len=str.length() ;
int result=0 ;
for(int i=0;i<len;i++)
{
int one=value(str[i]) ;
if(i+1<len)
{
int two=value(str[i+1]) ;
if(one>=two)
result+=one ;
else
{
result+=(two-one) ;
i++ ;
}
}
else
{
result+=one ;
i++ ;
}
}
return result ;
}
int main()
{
int t ;
cin>>t ;
while(t--)
{
string str ;
cin>>str ;
cout<<Roman2Integer(str)<<endl ;
}
return 0;
}
---------------------------------------------------------------------------------
Given an string in roman no format (s) your task is to convert it to integer .
Input:
The first line of each test case contains the no of test cases T. Then T test cases follow. Each test case contains a string s denoting the roman no.
Output:
For each test case in a new line print the integer representation of roman number s.
Constraints:
1<=T<=100
1<=roman no range<4000
Example:
Input
2
V
III
Output
5
3
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
#include<bits/stdc++.h>
using namespace std;
int value(char r)
{
if (r == 'I')
return 1;
if (r == 'V')
return 5;
if (r == 'X')
return 10;
if (r == 'L')
return 50;
if (r == 'C')
return 100;
if (r == 'D')
return 500;
if (r == 'M')
return 1000;
return 0 ;
}
int Roman2Integer(string str)
{
int len=str.length() ;
int result=0 ;
for(int i=0;i<len;i++)
{
int one=value(str[i]) ;
if(i+1<len)
{
int two=value(str[i+1]) ;
if(one>=two)
result+=one ;
else
{
result+=(two-one) ;
i++ ;
}
}
else
{
result+=one ;
i++ ;
}
}
return result ;
}
int main()
{
int t ;
cin>>t ;
while(t--)
{
string str ;
cin>>str ;
cout<<Roman2Integer(str)<<endl ;
}
return 0;
}
---------------------------------------------------------------------------------
Comments
Post a Comment