罗马数字转整数(java)

public int romanToInt(String s) {
        if(s.length() <= 0 ){
			return 0;
		}
		int res = 0;
		int len = s.length();
		char[] c = s.toCharArray();
		int index = 0;
		while(index < len  ){
			//M
			if(index <len && c[index] == 'M' ){
				res += 1000;
				index++;
				continue;
			}
			//C*
			if(c[index] == 'C'){
				index++;
				if(index <len &&c[index] == 'M' ){
					res += 900;
					index ++;
					continue;
				}else if(index <len &&c[index] == 'D' ){
					res += 400;
					index ++;
					continue;
				}else{ 
					index--;
					res += 100;
					index++;
					continue;
				}
			}
			//D
			if(index <len &&c[index] == 'D'  ){
				res += 500;
				index++;
				continue;
			}
			
			//X*
			if(c[index] == 'X'){
				index++;
				if( index <len&&c[index] == 'C' ){
					res += 90;
					index ++;
					continue;
				}else if(index <len && c[index] == 'L' ){
					res += 40;
					index ++;
					continue;
				}
				else{ 
					index--;
					res += 10;
					index++;
					continue;
				}
			}
			//L
			if(index <len && c[index] == 'L' ){
				res += 50;
				index++;
				continue;
			}
			//I*
			if(c[index] == 'I'){
				index++;
				if( index <len && c[index] == 'X' ){
					res += 9;
					index ++;
					continue;
				}else if( index <len&&c[index] == 'V'){
					res += 4;
					index ++;
					continue;
				}else{ 
					index--;
					res += 1;
					index++;
					continue;
				}
			}
			//V
			if(index <len && c[index] == 'V' ){
				res += 5;
				index++;
				continue;
			}
		}
		return res;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值