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;    }}


0 0
原创粉丝点击