前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode 13. Roman to Integer题目分析代码

LeetCode 13. Roman to Integer题目分析代码

作者头像
desperate633
发布2018-08-22 15:33:48
2380
发布2018-08-22 15:33:48
举报
文章被收录于专栏:desperate633desperate633

Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.

题目

给定一个罗马数字,将其转换成整数。 返回的结果要求在1到3999的范围内。 说明什么是 罗马数字? https://en.wikipedia.org/wiki/Roman_numerals https://zh.wikipedia.org/wiki/%E7%BD%97%E9%A9%AC%E6%95%B0%E5%AD%97 http://baike.baidu.com/view/42061.htm 样例IV -> 4 XII -> 12 XXI -> 21 XCIX -> 99

分析

运用hashmap

代码

代码语言:javascript
复制
public class Solution {
    /**
     * @param s Roman representation
     * @return an integer
     */
    public int romanToInt(String s) {
        if (s == null || s.length()==0) {
                return 0;
        }
        Map<Character, Integer> m = new HashMap<Character, Integer>();
        m.put('I', 1);
        m.put('V', 5);
        m.put('X', 10);
        m.put('L', 50);
        m.put('C', 100);
        m.put('D', 500);
        m.put('M', 1000);

        int length = s.length();
        int result = m.get(s.charAt(length - 1));
        for (int i = length - 2; i >= 0; i--) {
            if (m.get(s.charAt(i + 1)) <= m.get(s.charAt(i))) {
                result += m.get(s.charAt(i));
            } else {
                result -= m.get(s.charAt(i));
            }
        }
        return result;
    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017.03.26 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目
  • 分析
  • 代码
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档