标签:style blog io color ar sp div on log
这道题我是按定义来做的
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
1 package com.gxf.test; 2 3 public class Solution { 4 public int romanToInt(String s) { 5 int result = 0; 6 char array[] = s.toCharArray(); 7 int i = 0; 8 9 while (i < array.length) { 10 switch (array[i]) { 11 case ‘M‘:// 千位 12 while (i < array.length && array[i] == ‘M‘) { 13 result += 1000; 14 i++; 15 } 16 break; 17 case ‘C‘:// 百位 18 while (i < array.length && array[i] == ‘C‘) { 19 result += 100; 20 i++; 21 } 22 if (i < array.length && array[i] == ‘D‘) { 23 result += 300;// 前面加过100 24 i++; 25 }// CD 26 if (i < array.length && array[i] == ‘M‘) { 27 result += 800;// 前面加过100 28 i++; 29 }// CM 30 break; 31 case ‘D‘:// 百位500 32 i++; 33 result += 500; 34 while (i < array.length && array[i] == ‘C‘) { 35 result += 100; 36 i++; 37 } 38 break; 39 case ‘X‘:// 十位 40 while (i < array.length && array[i] == ‘X‘) { 41 result += 10; 42 i++; 43 } 44 if (i < array.length && array[i] == ‘L‘) { 45 result += 30; 46 i++; 47 } 48 if (i < array.length && array[i] == ‘C‘) { 49 result += 80; 50 i++; 51 } 52 break; 53 case ‘L‘: 54 i++; 55 result += 50; 56 while (i < array.length && array[i] == ‘X‘) { 57 result += 10; 58 i++; 59 }// 十位 60 break; 61 case ‘I‘:// 个位 62 while (i < array.length && array[i] == ‘I‘) { 63 result += 1; 64 i++; 65 } 66 if (i < array.length && array[i] == ‘V‘) { 67 result += 3; 68 i++; 69 } 70 if (i < array.length && array[i] == ‘X‘) { 71 result += 8; 72 i++; 73 } 74 break; 75 case ‘V‘: 76 result += 5; 77 i++; 78 while (i < array.length && array[i] == ‘I‘) { 79 result += 1; 80 i++; 81 } 82 } 83 } 84 85 return result; 86 } 87 88 }
标签:style blog io color ar sp div on log
原文地址:http://www.cnblogs.com/luckygxf/p/4087823.html