LeetCode13 roman to integer
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
从低位开始累加,注意一下像IV和 VI DC和CD的处理
class Solution { public: int romanToInt(string s) { int sStart = 0; int sEnd = s.size() - 1; int pScan = sEnd; int total = 0; if(sEnd < 0) { return -1; } while(pScan >= sStart) { if(s[pScan] == 'X' && total < 50) { total += 10; pScan--; } if(s[pScan] == 'X' && total >= 50) { total -= 10; pScan--; } else if(s[pScan] == 'V') { total += 5; pScan--; } else if(s[pScan] == 'I' && total < 5) { total += 1; --pScan; } else if(s[pScan] == 'I' && total >= 5) { total -= 1; --pScan; } else if(s[pScan] == 'L') { total += 50; pScan--; } else if(s[pScan] == 'C' && total < 500) { total += 100; pScan--; } else if(s[pScan] == 'C' && total >= 500) { total -= 100; pScan--; } else if(s[pScan] == 'D') { total += 500; pScan--; } else if(s[pScan] == 'M') { total += 1000; pScan--; } } return total; } };
if else 语句略长。
learn++