leetcode之旅(10)-Roman to Integer
来源:互联网 发布:c语言控制台编程 编辑:程序博客网 时间:2024/06/09 16:02
题目描述:
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
预备知识:
记数方法
基本字符
I
V
X
L
C
D
M
相应的阿拉伯数字表示为
1
5
10
50
100
500
1000
1、相同的数字连写,所表示的数等于这些数字相加得到的数,如:Ⅲ = 3;
2、小的数字在大的数字的右边,所表示的数等于这些数字相加得到的数, 如:Ⅷ = 8;Ⅻ = 12;
3、小的数字,(限于Ⅰ、X 和C)在大的数字的左边,所表示的数等于大数减小数得到的数,如:Ⅳ= 4;Ⅸ= 9;
4、正常使用时,连写的数字重复不得超过三次。(表盘上的四点钟“IIII”例外)
5、在一个数的上面画一条横线,表示这个数扩大1000倍。 ##
思路:
一个罗马字符对应一个数字权,那么就可以用数据结构map
对于s中出现的每一个罗马字符从右到左(无低位高位这么一说),如果权值在变大,则权相加
如果变小了,则减去这个权值 ##
代码:
import java.util.HashMap;import java.util.Map;public class Solution { public int romanToInt(String s) { int result=0; Map<Character,Integer> roman = new HashMap<Character,Integer>(); roman.put('I', 1); roman.put('V', 5); roman.put('X', 10); roman.put('L', 50); roman.put('C', 100); roman.put('D', 500); roman.put('M', 1000); for(int i=s.length()-1;i>=0;i--) { if(i==s.length()-1) { result=roman.get(s.charAt(i)); continue; } if(roman.get(s.charAt(i)) >= roman.get(s.charAt(i+1))) result+=roman.get(s.charAt(i)); else result-=roman.get(s.charAt(i)); } return result; }}
0 0
- leetcode之旅(10)-Roman to Integer
- leetcode之旅(11)-Integer to Roman
- leetcode之Roman to Integer
- LeetCode之Roman to Integer
- leetcode 之 Roman to Integer
- leetCode 之 Roman to Integer
- 【Leetcode】之Integer to Roman
- 【Leetcode】之Roman to Integer
- leetcode之Roman to Integer
- LeetCode 之 Roman to Integer
- Leetcode 之 Roman to Integer
- leetcode(10),Roman to Integer(python)
- leetcode之Roman to Integer && Integer to Roman
- LeetCode之Integer to Roman, Roman to Integer
- leetcode系列(35)Roman to Integer & Integer to Roman
- LeetCode Roman to Integer && Integer to Roman
- 【leetcode】Roman to Integer | Integer to Roman
- Leetcode - "Roman to Integer" & "Integer to Roman"
- 第5周项目1(4)三角形类雏形
- 【Android程序优化,避免内存泄露】- [实战一]:避免内存泄露的最后一道墙,使用leakcanary分析程序中的内存泄露。
- node.js 连接数据库
- Java并发:互斥锁和读写锁
- mysql查询中文出现乱码
- leetcode之旅(10)-Roman to Integer
- [C++]class内的static方法指针
- leetcode_021 Merge Two Sorted Lists
- 1014. 福尔摩斯的约会 (20)
- java.lang.ClassCastException: android.widget.ListView 替换控件出错 如自定义mlistview继承listview
- 大芝麻 APP
- Redis学习笔记(一)Redis数据库入门
- 欢迎使用CSDN-markdown编辑器
- LA5052