From 4094a8278868d5b78cbf3d215cecee7578aff05a Mon Sep 17 00:00:00 2001 From: Nitin Sahu Date: Sun, 28 Jul 2024 12:43:08 +0530 Subject: [PATCH] Roman to Integer in java --- .../Roman to Integer | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 Roman to Integer - Leetcode 13/Roman to Integer diff --git a/Roman to Integer - Leetcode 13/Roman to Integer b/Roman to Integer - Leetcode 13/Roman to Integer new file mode 100644 index 0000000..826a8e9 --- /dev/null +++ b/Roman to Integer - Leetcode 13/Roman to Integer @@ -0,0 +1,22 @@ +class Solution { + public int romanToInt(String s) { + Map 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 result=map.get(s.charAt(s.length()-1)); + for(int i=s.length()-2;i>=0;i--){ + if(map.get(s.charAt(i)) < map.get(s.charAt(i+1))){ + result-=map.get(s.charAt(i)); + }else{ + result+=map.get(s.charAt(i)); + } + } + return result; + } +}