Advertisement
CreateWithChirag

Roman To Integer

Apr 1st, 2023
1,029
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.79 KB | Source Code | 0 0
  1. class Solution {
  2.     public int romanToInt(String s) {
  3.         int ans =0, num =0, next=0;
  4.  
  5.         for(int i = s.length() -1; i >= 0; i--){
  6.             switch(s.charAt(i)){
  7.                 case 'M': num =1000;
  8.                 break;
  9.                 case 'D': num = 500;
  10.                 break;
  11.                 case 'C': num = 100;
  12.                 break;
  13.                 case 'L': num = 50;
  14.                 break;
  15.                 case 'X': num = 10;
  16.                 break;
  17.                 case 'V': num = 5;
  18.                 break;
  19.                 case 'I': num = 1;
  20.                 break;
  21.             }
  22.  
  23.             if(num < next){
  24.                 ans -= num;
  25.             }else{
  26.                 ans += num;
  27.             }
  28.             next = num;
  29.         }
  30.         return ans;
  31.     }
  32. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement