欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

解题报告 13 Easy

程序员文章站 2022-01-15 12:00:04
...

https://leetcode.com/problems/roman-to-integer

	public static int singleCharToInt(char ch) {
		int num = 0;
		switch (ch) {
		case 'I':
			num = 1;
			break;
		case 'V':
			num = 5;
			break;
		case 'X':
			num = 10;
			break;
		case 'L':
			num = 50;
			break;
		case 'C':
			num = 100;
			break;
		case 'D':
			num = 500;
			break;
		case 'M':
			num = 1000;
			break;
		}
		return num;
	}
	public static int romanToInt(String s) {
		if(s.length() ==1) return singleCharToInt(s.charAt(0));
		int sum = 0,len = s.length();
		
		for (int i = 0; i < len; i++) {
			if(s.charAt(i) == 'I') {
				if(i<len-1) {
					if(s.charAt(i+1) == 'V') {
						System.out.println("----IV");
						sum += 4;
					}else if(s.charAt(i+1) == 'X') {
						System.out.println("----IX");
						sum += 9;
					}else {
						sum += 1;
					}
				}else {
					sum += singleCharToInt(s.charAt(i));
				}
				
			}
			
			else if(s.charAt(i) == 'X') {
				if(i<len-1) {
					if(s.charAt(i+1) == 'L') {
						sum += 40;
					}else if(s.charAt(i+1) == 'C') {
						sum += 90;
					}else {
						sum += 10;
					}
				}else {
					sum += singleCharToInt(s.charAt(i));
				}
			}
			else if(s.charAt(i) == 'C') {
				if(i<len-1) {
					if(s.charAt(i+1) == 'D') {
						sum += 400;
					}else if(s.charAt(i+1) == 'M') {
						sum += 900;
					}else {
						sum += 100;
					}
				}else {
					sum += singleCharToInt(s.charAt(i));
				}
			}
			else {
				sum += singleCharToInt(s.charAt(i));
			}
		}
		
		
		return sum;
	}

相关标签: leetcode