Monday, December 31, 2012

[LeetCode] Roman To Integer 解题报告


Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
» Solve this problem

[解题思路]

从前往后扫描,用一个临时变量记录分段数字。
  • 如果当前比前一个大,说明这一段的值应该是当前这个值减去上一个值。比如IV = 5 – 1
  • 否则,将当前值加入到结果中,然后开始下一段记录。比如VI = 5 + 1, II=1+1



[Code]
1:    inline int c2n(char c) {  
2:      switch(c) {  
3:        case 'I': return 1;  
4:        case 'V': return 5;  
5:        case 'X': return 10;  
6:        case 'L': return 50;  
7:        case 'C': return 100;  
8:        case 'D': return 500;  
9:        case 'M': return 1000;  
10:        default: return 0;  
11:      }  
12:    }  
13:    int romanToInt(string s) {  
14:      // Start typing your C/C++ solution below  
15:      // DO NOT write int main() function  
16:      int result=0;  
17:      for(int i =0; i< s.size(); i++)  
18:      {  
19:        if(i>0&& c2n(s[i]) > c2n(s[i-1]))  
20:        {  
21:          result +=(c2n(s[i]) - 2*c2n(s[i-1]));  
22:        }  
23:        else  
24:        {  
25:          result += c2n(s[i]);  
26:        }  
27:      }  
28:      return result;  
29:    }  


关联题:
http://fisherlei.blogspot.com/2012/12/leetcode-integer-to-roman.html



No comments: