package javaLeetCode.primary;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Stack;
public class RomanToInteger_13 {
public static void main(String[] args) {
System.out.println("Please input a roman numeral:");
@SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
String s = input.next();
System.out.println(romanToInt_3(s));
}
public static int romanToInt_1(String s) {
char[] str = s.toCharArray();
Map<Character, Integer> map = new HashMap<Character, Integer>();
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 num = 0;
for (int i = 0; i < s.length() - 1; i++) {
if (map.get(str[i]) >= map.get(str[i + 1])) {
num += map.get(str[i]);
} else {
num -= map.get(str[i]);
}
}
num += map.get(str[str.length - 1]);
return num;
}
public static int romanToInt_2(String s) {
char[] str = s.toCharArray();
Stack <Integer>romanStack = new Stack<Integer>();
Map<Character, Integer> map = new HashMap<Character, Integer>();
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 num = 0;
romanStack.push(map.get(str[0]));
for (int i = 1; i < s.length() ; i++) {
if (map.get(str[i]) <= map.get(str[i - 1])) {
romanStack.push(map.get(str[i]));
} else {
romanStack.push(map.get(str[i])-romanStack.pop());
}
}
int length = romanStack.size();
for(int i=0;i<length;i++) {
num += romanStack.pop();
}
return num;
}
public static int romanToInt_3(String s) {
int num = 0;
for(int i=0;i<s.length();i++) {
char c = s.charAt(i);
if(c=='I') {num += 1;}
if(c=='V') {num += 5;}
if(c=='X') {num += 10;}
if(c=='L') {num += 50;}
if(c=='C') {num += 100;}
if(c=='D') {num += 500;}
if(c=='M') {num += 1000;}
}
if(s.contains("IV")) {num -= 2;}
if(s.contains("IX")) {num -= 2;}
if(s.contains("XL")) {num -= 20;}
if(s.contains("XC")) {num -= 20;}
if(s.contains("CD")) {num -= 200;}
if(s.contains("CM")) {num -= 200;}
return num;
}
}
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Java 中堆内存和栈内存上的数据分布和特点
· 开发中对象命名的一点思考
· .NET Core内存结构体系(Windows环境)底层原理浅谈
· C# 深度学习:对抗生成网络(GAN)训练头像生成模型
· .NET 适配 HarmonyOS 进展
· 如何给本地部署的DeepSeek投喂数据,让他更懂你
· 超详细,DeepSeek 接入PyCharm实现AI编程!(支持本地部署DeepSeek及官方Dee
· 用 DeepSeek 给对象做个网站,她一定感动坏了
· .NET 8.0 + Linux 香橙派,实现高效的 IoT 数据采集与控制解决方案
· .NET中 泛型 + 依赖注入 的实现与应用