当前位置: 首页 > news >正文

[Java][Leetcode simple] 13. 罗马数字转整数

一、自己想的

只有提到的六种情况是-,其他都是+

 public int romanToInt1(String s) {int res = 0;int n = s.length();Map<Character, Integer> map = new HashMap<>();map.put('I', 1);map.put('V', 5);map.put('X', 10);map.put('L', 50);map.put('C', 100);map.put('D', 500);map.put('M', 1000);int flag;for( int i =n-1; i>=0; i-- ) {char c = s.charAt(i);flag = 1;if(c == 'I' && i != n-1  ) {if(s.charAt(i+1) == 'V' || s.charAt(i+1) == 'X') {flag = 0;}}else if(c == 'X' && i != n-1) {if(s.charAt(i+1) == 'L' || s.charAt(i+1) == 'C') {flag = 0;}} else if (c == 'C' && i != n-1) {if(s.charAt(i+1) == 'D' || s.charAt(i+1) == 'M') {flag = 0;}}if(flag == 0){res -= map.get(c);}else {res += map.get(c);}}return res;}

二、官方题解

倒序遍历,观察到,只要n[i]>n[i-1]就是减(例如IV),其余情况是加.
当然上述情况和六种情况是充要条件,因为比如"IM"这种是非法罗马数字。
在这里插入图片描述

 public int romanToInt1(String s) {int res = 0;int n = s.length();Map<Character, Integer> map = new HashMap<>();map.put('I', 1);map.put('V', 5);map.put('X', 10);map.put('L', 50);map.put('C', 100);map.put('D', 500);map.put('M', 1000);for( int i =n-1; i>=0; i-- ) {int num = map.get(s.charAt(i));if(i!=n-1 &&  num < map.get(s.charAt(i+1)) ) {res -= num;}else{res += num;}}return res;}

文章转载自:

http://AceeYI00.fbxdp.cn
http://AceGUbGv.fbxdp.cn
http://pcI0Mytm.fbxdp.cn
http://d9Oc7Cmj.fbxdp.cn
http://mh44Ix4L.fbxdp.cn
http://MrjMiB8m.fbxdp.cn
http://RrBiijXq.fbxdp.cn
http://EedNOcmk.fbxdp.cn
http://L9G1bHsn.fbxdp.cn
http://imYjjdZz.fbxdp.cn
http://5D4YHIb7.fbxdp.cn
http://CdBpCiHr.fbxdp.cn
http://edkP8zdZ.fbxdp.cn
http://ISOBwslW.fbxdp.cn
http://sW11gCrN.fbxdp.cn
http://wx2zLHuw.fbxdp.cn
http://mcANMnbF.fbxdp.cn
http://FSDjh9Jl.fbxdp.cn
http://it7SY4UJ.fbxdp.cn
http://kwpsjdMn.fbxdp.cn
http://zpmdCUIL.fbxdp.cn
http://gGs7QdxE.fbxdp.cn
http://bkUZ7EzQ.fbxdp.cn
http://3hliaYYV.fbxdp.cn
http://aBTKpFFb.fbxdp.cn
http://arGvl5wC.fbxdp.cn
http://m9NNItnx.fbxdp.cn
http://r1RmDGJf.fbxdp.cn
http://e0Jt5l6r.fbxdp.cn
http://VyrQ0Uag.fbxdp.cn
http://www.dtcms.com/a/195884.html

相关文章:

  • SLAM定位常用地图对比示例
  • 系分论文《论系统需求分析方法及应用》
  • Redis深度解析:高性能内存数据库的核心原理与应用实践
  • Rhino 8 犀牛保姆级安装教程
  • 常见的实时通信技术(轮询、sse、websocket、webhooks)
  • 从辅助到协作:GitHub Copilot的进化之路
  • Vue 3.0中响应式依赖和更新
  • 天拓四方锂电池卷绕机 PLC 物联网解决方案
  • Maven 插件扩展点与自定义生命周期
  • p024基于Django的网上购物系统的设计与实现
  • 如何免费在线PDF转换成Excel
  • Netty的简单使用
  • 自己手写tomcat项目
  • C++数据结构 —— 平衡树Treap
  • Bellman - Ford 算法与 SPFA 算法求解最短路径问题 ——从零开始的图论讲解(4)
  • OTA与boot loader
  • 基于QT和FFmpeg实现自己的视频播放器FFMediaPlayer(一)——项目总览
  • 38-日语学习小程序
  • Rust 编程语言的官方源码仓库
  • Python爬虫-爬取百度指数之人群兴趣分布数据,进行数据分析
  • Python标准库完全指南:os、sys与math模块详解与实战应用
  • 【论文阅读】人脸修复(face restoration ) 不同先验代表算法整理2
  • 【Java ee初阶】HTTP(2)
  • 【OpenCV】基本数据类型及常见图像模式
  • C++(初阶)(十八)——AVL树
  • JavaScript【5】DOM模型
  • 反射机制动态解析
  • 【springcloud学习(dalston.sr1)】Config配置中心-ConfigServer端与Git通信(含源代码)(十三)
  • JAVA Spring MVC+Mybatis Spring MVC的工作流程*
  • 深入解析SpringMVC:从入门到精通