#13 LeetCode——Roman to Integer
2015-09-28 17:19
543 查看
将罗马字符转化为阿拉伯数字表示
注:罗马数字表示:I(1)、V(5)、X(10)、L(50)、C(100)、D(500)、 M(1000)
阿拉伯数字 | 罗马数字 |
---|---|
1 | I |
4 | IV |
5 | V |
9 | IX |
10 | X |
50 | L |
100 | V |
500 | D |
1000 | M |
java代码如下
public class Solution { public int romanToInt(String s) { char[] nums = s.toCharArray(); int result = 0; int[] values = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 }; for (int i = 0; i < nums.length; i++) { //1000 if(nums[i] == 'M') { result += 1000; } //100 if(nums[i] == 'C' && i + 1 < nums.length) { if(nums[i + 1] == 'M' || nums[i + 1] == 'D') { result -= 100; } else { result += 100; } } else if(nums[i] == 'C') { result += 100; } //500 if(nums[i] == 'D') { result += 500; } //10 if(nums[i] == 'X' && i + 1 < nums.length) { if(nums[i + 1] == 'C' || nums[i + 1] == 'L') { result -= 10; } else { result += 10; } } else if(nums[i] == 'X') { result += 10; } //50 if(nums[i] == 'L') { result += 50; } //1 if(nums[i] == 'I' && i + 1 < nums.length) { if(nums[i + 1] == 'X' || nums[i + 1] == 'V') { result -= 1; } else { result += 1; } } else if(nums[i] == 'I') { result += 1; } //5 if(nums[i] == 'V') { result += 5; } } return result; } }
相关文章推荐
- C#线程编程实例
- Django+python+BeautifulSoup垂直搜索爬虫
- android内存管理
- Android 5.x的Activity过渡动画.
- linux下ssh安装 和 scp命令 使用
- UVA 12627 Erratic Expansion
- python-requests快速上手
- SVN服务器搭建和使用(四)
- _INTSIZEOF(n)
- Bug:__uClibc_main.c:(.text+0x20): undefined reference to `__fini_array_start'问题的解决
- 用Python学习统计学基础-5
- js 小知识
- hadoop计数器
- python [1:3]
- Flex和Flash的区别
- 心情
- URAL 1205 By the Underground or by Foot (建图 + Dijkstra迪杰斯特拉算法)
- 个人对堆栈的理解和IAR编译器的内存分配
- java 初始化(下)
- SQL Server学习记录之递增生成注册ID号