13. Roman to Integer LeetCode题解
来源:互联网 发布:网络打鱼赌钱游戏微信 编辑:程序博客网 时间:2024/05/17 14:20
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
Subscribe to see which companies asked this question.
题意:
给定一个罗马数字,将其转换为整数。
输入数据范围从1到3999
题解:
罗马数字规则
根据规则,左减的数字有限制,仅限于I、X、C,且最多一位,该位小于其右侧的数字,
则只有在s[i] < s[i + 1]时才减去s[i]对应的值,否则加上s[i]对应的值
Code【Java】
public class Solution { static String str = "IVXLCDM"; static int[] nums = {1, 5, 10, 50, 100, 500, 1000}; public int romanToInt(String s) { int ans = 0; for (int i = 0; i < s.length() - 1; ++i) { int index = str.indexOf(s.charAt(i)); int index2= str.indexOf(s.charAt(i + 1)); ans += (index < index2) ? -nums[index] : nums[index]; } ans += nums[str.indexOf(s.charAt(s.length() - 1))]; return ans; }}
Code【C++】
class Solution { string str = "IVXLCDM"; int nums[7] = {1, 5, 10, 50, 100, 500, 1000};public: int romanToInt(string s) { int ans = 0; for (int i = 0; i < s.length() - 1; ++i) { int index = str.find(s[i]); int index2= str.find(s[i + 1]); ans += (index < index2) ? -nums[index] : nums[index]; } ans += nums[str.find(s[s.length() - 1])]; return ans; }};
阅读全文
0 0
- 13. Roman to Integer LeetCode题解
- leetcode题解-13. Roman to Integer
- LeetCode题解:Roman to Integer
- LeetCode题解:Integer to Roman
- LeetCode题解:Roman to Integer
- LeetCode题解:Integer to Roman
- LeetCode 13. Roman to Integer 题解(C++)
- LeetCode 题解(58): Integer to Roman
- LeetCode 题解(73): Roman to Integer
- leetcode题解||Integer to Roman问题
- leetcode题解 || Roman to Integer问题
- LeetCode题解——Roman to Integer
- LeetCode题解——Integer to Roman
- LeetCode 12 Integer to Roman题解
- LeetCode题解-12-Integer to Roman
- LeetCode题解-13-Roman to Integer
- 12. Integer to Roman LeetCode题解
- leetcode题解-12. Integer to Roman
- 计算机网络漫谈之OSI七层模型和TCP/IP四层模型
- 网站如何定位用户省份?
- oracle中常用函数大全
- 使用Spring特性实现接口多实现类的动态调用
- android Spinner控件详解
- 13. Roman to Integer LeetCode题解
- iOS 通知 遇到的坑
- 逐漸體會....
- 使用 Ceph-deploy 快速部署 Ceph 环境
- unity闪退log。主要是堆log查看。
- 分布式ActiveMQ集群
- u3d协程控制匀速旋转角度
- 震惊:70%的人投简历七天内就有回音
- Android M 动态权限获取