标签:方法 color order ++ htable int span 等于 相同
方法:注意罗马数字的分布即可
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; i<13; ++i) { while(num >= value[i]) { str += symbol[i]; num -= value[i]; } } return str; } };
Roman to Integer规则:
class Solution { public: int romanToInt(string s) { char symbol[]={‘M‘,‘D‘,‘C‘,‘L‘,‘X‘,‘V‘,‘I‘}; int value[]= {1000, 500, 100, 50, 10, 5, 1}; unordered_map<char, int>hashTable; for(int i=0; i<7; ++i) hashTable[symbol[i]] = value[i]; int result = 0; for(int i=0; i<s.size(); ++i) { if(i>0 && hashTable[s[i]] > hashTable[s[i-1]]) { result += hashTable[s[i]] - 2*hashTable[s[i-1]]; } else result += hashTable[s[i]]; } return result; } };
Integer to Roman/Roman to Integer
标签:方法 color order ++ htable int span 等于 相同
原文地址:http://www.cnblogs.com/chengyuz/p/6752067.html