欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 艺术 > [Java][Leetcode simple] 13. 罗马数字转整数

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

2025/5/18 6:24:16 来源:https://blog.csdn.net/shijizhe1/article/details/148036012  浏览:    关键词:[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;}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词