首页 > 代码库 > [LeetCode]Roman to Integer
[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.
class Solution { public: int romanToInt(string s) { int roman[128]; roman[‘I‘] = 1; roman[‘V‘] = 5; roman[‘X‘] = 10; roman[‘L‘] = 50; roman[‘C‘] = 100; roman[‘D‘] = 500; roman[‘M‘] = 1000; int ans = 0; int pre; //大数后面是小数,则减; //大数前面是小数,则加; for(int i = s.size() - 1; i >= 0; i--) { if(ans == 0) { ans = roman[s[i]]; } else { if(pre > roman[s[i]]) { ans -= roman[s[i]]; } else { ans += roman[s[i]]; } } pre = roman[s[i]]; } return ans; } };
罗马数字简介,参考:
[LeetCode]Integer to Roman - Jet_yingjia的专栏 - 博客频道 - CSDN.NET
http://blog.csdn.net/jet_yingjia/article/details/25814977
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。