Share Sinple Easy JAVA Solution


  • 0
    public static int romanToInt(String s)
    {
      //只要处理例如IV、CD这样的表示,其他直接一路加下来就好了
      int[] carr=new int[128];
      carr['I']=1;
      carr['V']=5;
      carr['X']=10;
      carr['L']=50;
      carr['C']=100;
      carr['D']=500;
      carr['M']=1000;
      int num=0;
      int i=0;
      for(;i<s.length()-1;)
      {
         if(carr[s.charAt(i+1)]<=carr[s.charAt(i)])
    	{
    	  num+=carr[s.charAt(i)];
    	  i++;
    	}
         else {
    	  num+=carr[s.charAt(i+1)];
    	  num-=carr[s.charAt(i)];
    	  i+=2;
    	  }
      }
         if(i<s.length())
    	  num+=carr[s.charAt(i)];
         return num;
    }
    
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.