Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Ayoub Ali
Ayoub Ali

Posted on

     

Roman to Integer in Dart - Leetcode

Roman to Integer

Approach

  1. Maintain a map with roman symbol and their corresponding integer equivalent - Already given in the question

  2. Scan the string from right to left. Get the corresponding value to the current character from the map and add into to result

  3. The special case is where the character at the left of the current character whose value is less than the value corresponding to the current character. For e.g x represent 10, but IX represents 9. In this case we have we subtract the value of the character in the left from the result

Code

Both Solutions are perfectly fine but first one pass with flying colors and other one end up with fatal and most annoying error I think or believe it something that while loop is broken, or maybe it does execute properly on leetCode platform

Simple Solution

classSolution{intromanToInt(Strings){Map<String,int>romanMap=<String,int>{"I":1,"V":5,"X":10,"L":50,"C":100,"D":500,"M":1000,};intn=s.length;varnums=romanMap[s[n-1]];for(vari=n-2;i>=0;i--){if(romanMap[s[i]]!>=romanMap[s[i+1]]!){if(nums!=null){nums+=romanMap[s[i]]!;}}else{if(nums!=null){nums-=romanMap[s[i]]!;}}}returnnums!;}}
Enter fullscreen modeExit fullscreen mode

Runtime: 841 ms, faster than 88.89% of Dart online submissions for Roman to Integer.
Memory Usage: 149.6 MB, less than 66.67% of Dart online submissions for Roman to Integer.

Algorithmic Solution

classSolution{intromanToInt(Strings){intgetInt(Strings){switch(s){case"I":return1;case"V":return5;case"X":return10;case"L":return50;case"C":return100;case"D":return500;case"M":return1000;default:-1;}return0;}intn=s.length;intresult=0;intcurrent=0;intnext=0;inti=0;while(i<n){if(i==n-1){result+=getInt(s[i]);returnresult;}current=getInt(s[i]);next=getInt(s[i+1]);if(current>=next){result+=current;i++;}else{result+=next-current;i+=2;}}returnresult;}}
Enter fullscreen modeExit fullscreen mode

Error

Submission Detail
64 / 3999 test cases passed.
Status: Time Limit Exceeded
Last executed input: "MCXXV"

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

AI Engineer | Programmer | Security Researcher
  • Work
    Freelancer - Looking for Opportunities
  • Joined

More fromAyoub Ali

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp