Roman to Integer 罗马数字转化成整数
来源:互联网 发布:天府商品交易软件 编辑:程序博客网 时间:2024/05/16 18:24
题目:https://leetcode.com/problems/roman-to-integer/description/
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
题目大意:将罗马数字转换成整数。
解法:
1、罗马数字放进map,数字一一对应,
2、字符串每个都分割,从map中取出对应的值
3、第一,如果当前数字是最后一个数字,或者之后的数字小于等于他(<=)的话,则加上当前数字
第二,其他情况则减去这个数字
public static int romanToInt(String s) {int result=0;//1、罗马数字放进map,数字一一对应,Map<Character, Integer> romanInteger=new HashMap<Character, Integer>();romanInteger.put('I', 1);romanInteger.put('V', 5);romanInteger.put('X', 10);romanInteger.put('L', 50);romanInteger.put('C', 100);romanInteger.put('D', 500);romanInteger.put('M', 1000);//2、字符串每个都分割,从map中取出对应的值for (int i = 0; i < s.length(); i++) {if(i==s.length()-1){//如果当前数字是最后一个数字,加上result+=romanInteger.get(s.charAt(i));continue;}//之后的数字比它小的话,则加上当前数字boolean compare=false;for (int j = i+1; j < s.length(); j++) {if(romanInteger.get(s.charAt(i))<romanInteger.get(s.charAt(j))){compare=true;}}if(!compare){result+=romanInteger.get(s.charAt(i));continue;}//除此之外,则减去当前数字result-=romanInteger.get(s.charAt(i));}return result;}
参考自:http://www.cnblogs.com/grandyang/p/4120857.html
阅读全文
0 0
- Roman to Integer 罗马数字转化成整数
- Roman to Integer 罗马数字转化成整数
- Roman to Integer 罗马数字转化为整数
- leetcode-13. Roman to Integer(罗马数字转化成整数)
- Integer to Roman 整数转换成罗马数字
- Roman to Integer 罗马数字转换成整数
- leetcode_12. Integer to Roman 整数转化为罗马数字
- [LeetCode]13. Roman to Integer(罗马数字转化为整数)
- [LeetCode]12. Integer to Roman(整数转化为罗马数字)
- LeetCode | Integer to Roman(整数转换成罗马数字)
- LeetCode | Roman to Integer(罗马数字转换成整数)
- Roman to Integer(罗马数字转换成整数)
- leetcode-12. Integer to Roman(整数转换成罗马数字)
- Integer to Roman (整数转为罗马数字)
- Roman to Integer 罗马数字转为整数
- Integer to Roman 整数转罗马数字
- [LeetCode]Integer to Roman整数转罗马数字
- *[lintcode] Integer to Roman 整数转罗马数字
- 第十一篇:Bug管理系统UML2.0建模实例(三)
- Hello Kotlin
- jquery选择器
- Servlet 什么时候用页面重定向,什么时候用请求转发。
- easyUI入门--1
- Roman to Integer 罗马数字转化成整数
- vs编译器cl使用
- ARP
- C语言实现身份证查询系统
- 做人,赢在格局 ,输在计较!
- 关于HTTP协议
- 虚拟内存(占坑)
- Android开发之获取手机通讯录
- Add to List 167. Two Sum II