LeetCode--No.13--Roman to Integer
来源:互联网 发布:联想笔记本网络开关 编辑:程序博客网 时间:2024/06/07 01:34
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
这道easy也是费了好大尽。出错的地方如下:
1. Map<数据类型>,尖括号里的数据类型需要使用引用类型。
原始类型 封装类
boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double
关于引用类型与原始类型的区别,转载自: http://blog.sina.com.cn/s/blog_4586764e0100dr4r.html
原始类型是类
引用类型是对象
原始类型大小比较用"=="
引用类型大小比较用"equals"
引用类型可以被序列化,原始类型不行。
引用类型提供的方法可以灵活转换,可以扩展,原始类型不行
在集合类中只能使用引用类型,不能使用原始类型
原始类型没有null的概念,引用类型有,某些情况下需要辨别某个参数是否被初始化了,如果使用原始类型,那么0的值不知道是初始值还是没有初始化系统自动给的。
有些时候必须要用封装类,比如你要用
request.setAttribute(String key ,Object value);这个方法时,第二个参数为Object类型 ,而你要放的是一个整数的时候,那就只能放Integer不能放int。
2. roman.put() 向map中插入数据时,因为数据类型是Character, 所以要使用单引号。双引号则是String
思路: 从后向前扫描,中间位置的数字是最大的,只要不小于前面的数,就全部加在一起。最左面的数字,如果比主数字小的话,是要减掉的。
public class Solution { public int romanToInt(String s) { 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); if(s.equals(null)) return 0; int res = 0; char[] c = s.toCharArray(); for(int i = c.length - 1; i>=0; i--){ if (i == c.length -1){ res = roman.get(c[i]); continue; } else{ if (roman.get(c[i]) >= roman.get(c[i+1])) res += roman.get(c[i]); else res -= roman.get(c[i]); } } return res; }}
- Leetcode NO.13 Roman to Integer
- LeetCode--No.13--Roman to Integer
- LeetCode No.13 Roman to Integer
- 每日一练之Roman to integer & integer to Roman【LeetCode No.12,13】
- LeetCode--No.12--Integer to Roman
- leetcode-13:Roman to Integer
- leetcode 13 Roman to Integer
- Leetcode【13】:Roman to Integer
- [leetcode 13] Roman to Integer
- [Leetcode] 13 - Roman to Integer
- LeetCode | #13 Roman to Integer
- leetcode.13---------Roman to Integer
- leetCode #13 Roman to Integer
- leetcode-13 Roman to Integer
- leetcode 13 Roman to Integer
- LeetCode 13 Roman to Integer
- LeetCode 13 - Roman to Integer
- leetcode 13 -- Roman to Integer
- 【3D计算机图形学】变换矩阵、欧拉角、四元数
- 树莓派学习系列6——Sonic Pi音乐编程
- C++编码转换函数代码
- Python dis 模块初步使用
- MyEclipse导入jquery-1.8.0.min.js等文件报错的解决方案
- LeetCode--No.13--Roman to Integer
- ThreadLocal的简单入门使用
- shared_ptr的自定义析构函数的作用在于搭建一座桥
- LeetCode--No.12--Integer to Roman
- final的初始化
- Openstack组件部署 — Keystone Install & Create service entity and API endpoints
- LVS-DR模型实现负载均衡
- EasySwift/EasyEmoji ios或者swift匹配判断emoji
- kruskal最小生成树(MST)算法