您的位置:首页 > 其它

[LeetCode]13. Roman to Integer

2016-03-06 11:15 267 查看
Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

思路:建立一个与字符串等长的数组存放标志位,遍历整个字符串,若该的字符所表示的数字比其右边相邻的字符表示的数字小,则标志位记为-1;

否则记为1

将对应的字符表示的数字与相应的标志位相乘,做和得出结果

    
<span style="white-space:pre">	</span>public int romanToInt(String s) {
<span style="white-space:pre">		</span>if (s == null) return 0;
<span style="white-space:pre">		</span>
<span style="white-space:pre">			</span>char [] temp = s.toCharArray();
<span style="white-space:pre">			</span>int [] it = new int[temp.length];
<span style="white-space:pre">			</span>int [] a = new int[temp.length];
<span style="white-space:pre">			</span>int sum = 0;
<span style="white-space:pre">			</span>final  char I = 'I';
<span style="white-space:pre">			</span>final  char X = 'X';
<span style="white-space:pre">			</span>final  char L = 'L';
<span style="white-space:pre">			</span>final  char C = 'C';
<span style="white-space:pre">			</span>final  char D = 'D';
<span style="white-space:pre">			</span>final  char M = 'M';
<span style="white-space:pre">			</span>final  char V = 'V';
<span style="white-space:pre">			</span>for (int i = 0; i < temp.length; i++) {
<span style="white-space:pre">				</span>char t = temp[i];
<span style="white-space:pre">				</span>switch(t) {
<span style="white-space:pre">				</span>case I : it[i] = 1; break;
<span style="white-space:pre">				</span>case V : it[i] = 5; break;
<span style="white-space:pre">				</span>case X : it[i] = 10;break;
<span style="white-space:pre">				</span>case L : it[i] = 50; break;
<span style="white-space:pre">				</span>case C : it[i] = 100; break;
<span style="white-space:pre">				</span>case D : it[i] = 500; break;
<span style="white-space:pre">				</span>case M : it[i] = 1000; break;
<span style="white-space:pre">				</span>}
<span style="white-space:pre">				</span>for (int j = 0; j < it.length-1; j++) {
<span style="white-space:pre">					</span>if (it[j] < it[j+1]) a[j] = -1;
<span style="white-space:pre">					</span>else a[j] = 1;
<span style="white-space:pre">						</span>
<span style="white-space:pre">					</span>}
<span style="white-space:pre">				</span>}
<span style="white-space:pre">				</span>
<span style="white-space:pre">				</span>a[temp.length-1] = 1;
<span style="white-space:pre">				</span>for(int m = 0;m < temp.length; m++) {
<span style="white-space:pre">					</span>sum = sum + it[m]*a[m];
<span style="white-space:pre">				</span>}
<span style="white-space:pre">				</span>return sum;
<span style="white-space:pre">			</span>
<span style="white-space:pre">		</span>}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: