Advertisement
chmilar

romanToInt-1

Sep 28th, 2016
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.89 KB | None | 0 0
  1. public class Solution {
  2.     public int romanToInt(String s) {
  3.         s = s.toLowerCase();
  4.         int i = 0;
  5.         int total = 0;
  6.         while (i < s.length() - 1) {
  7.             int a = romanValue(s.charAt(i));
  8.             int b = romanValue(s.charAt(i+1));
  9.             if (b > a) {
  10.                 total += b - a;
  11.                 i += 2;
  12.             } else {
  13.                 total += a;
  14.                 i++;
  15.             }
  16.         }
  17.         if (i < s.length())
  18.             total += romanValue(s.charAt(s.length() - 1));
  19.         return total;
  20.     }
  21.    
  22.     private int romanValue(char c) {
  23.         switch (c) {
  24.             case 'i': return 1;
  25.             case 'v': return 5;
  26.             case 'x': return 10;
  27.             case 'l': return 50;
  28.             case 'c': return 100;
  29.             case 'd': return 500;
  30.             case 'm': return 1000;
  31.         }
  32.         return 0;
  33.     }
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement