leetcode记录 13. Roman to Integer

来源:互联网 发布:js删除数组中的对象 编辑:程序博客网 时间:2024/06/08 00:19

还是直接上代码吧,清晰易懂:

ublic int romanToInt(String s) {          int result = 0 ;          char[] digits = s.toCharArray();          if(digits.length > 0){              /* Initialize value map for Roman chars  */              int[] valueMap = new int[26];              valueMap['I' - 'A'] = 1;              valueMap['V' - 'A'] = 5;              valueMap['X' - 'A'] = 10;              valueMap['L' - 'A'] = 50;              valueMap['C' - 'A'] = 100;              valueMap['D' - 'A'] = 500;              valueMap['M' - 'A'] = 1000;              int lastIndex = digits[0] - 'A';              result = valueMap[lastIndex];              for(int i = 1 ; i < digits.length ; i++){                  int currentIndex = digits[i] - 'A';                   // If previous number was smaller in value then remove the previous and decrease the current value by previous value                  if(valueMap[lastIndex] < valueMap[currentIndex]){                       result = result - 2*valueMap[lastIndex] + valueMap[currentIndex] ;                  }else{                      result+= valueMap[currentIndex]; // just add the current value                  }                  lastIndex = currentIndex; // update last index              }          }          return result;      }

循环中<的情况要减两次2*什么的。

思想是:不管怎么样先加,出现满足的条件,再把之前已经加的值从中减去

0 0
原创粉丝点击