标签:
class Solution {
public:
int romanToInt(string s) {
int length = s.size();
int result = 0;
int pre =getnum (s[0]);
for (int i = 1 ;i<length ;i++)
{int current = getnum(s[i]);
//if (pre*5==current||pre*10==current)从左到右,如果当前值比右边的值小,则减去当前值,否则加上当前的值
if(pre<current)
result = result-pre;
else
result = result+pre;
pre = current;
}
return result+pre ;
}
int getnum(char c)
{//I(1)、V(5)、X(10)、L(50)、C(100)、D(500)、M(1000)
if (c==‘I‘)
return 1;
if (c==‘V‘)
return 5;
if (c==‘X‘)
return 10;
if (c==‘L‘)
return 50;
if (c==‘C‘)
return 100;
if (c==‘D‘)
return 500;
if (c==‘M‘)
return 1000;
}
};
标签:
原文地址:http://www.cnblogs.com/gofighting/p/5036129.html