(1) Roman to Integer -- Leetcode
Given a roman numeral, convert it to an integer.
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
/* Romans:
I V X L C D M
1 5 10 50 100 500 1000
*/
Answer:class Solution {
public:
inline int c2n(char c) {
switch(c) {
case 'I': return 1;
case 'V': return 5;
case 'X': return 10;
case 'L': return 50;
case 'C': return 100;
case 'D': return 500;
case 'M': return 1000;
default: return 0;
}
}
int romanToInt(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int result=0;
for(int i =0; i< s.size(); i++)
{
if(i>0&& c2n(s[i]) > c2n(s[i-1]))
{
result +=(c2n(s[i]) - 2*c2n(s[i-1]));
}
else
{
result += c2n(s[i]);
}
}
return result;
}
};
(2) Integer to Roman -- Leetcode
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
class Solution {
public:
string intToRoman(int num) {
string str;
string symbol[]={"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
int value[]= {1000,900,500,400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
for(int i=0;num!=0;++i)
{
while(num>=value[i])
{
num-=value[i];
str+=symbol[i];
}
}
return str;
}
};
No comments:
Post a Comment