Solve roman-to-integer.
This commit is contained in:
		
							parent
							
								
									bb5741755e
								
							
						
					
					
						commit
						83bb499e03
					
				| 
						 | 
				
			
			@ -2,5 +2,6 @@ pub mod implement_strstr;
 | 
			
		|||
pub mod longest_common_prefix;
 | 
			
		||||
pub mod palindrome_number;
 | 
			
		||||
pub mod reverse_integer;
 | 
			
		||||
pub mod roman_to_integer;
 | 
			
		||||
pub mod two_sum;
 | 
			
		||||
pub mod valid_parenthesis;
 | 
			
		||||
| 
						 | 
				
			
			
 | 
			
		|||
| 
						 | 
				
			
			@ -0,0 +1,44 @@
 | 
			
		|||
pub fn roman_to_int(string: String) -> i32 {
 | 
			
		||||
  let mut characters = string.chars().peekable();
 | 
			
		||||
  let mut number = 0;
 | 
			
		||||
 | 
			
		||||
  while let Some(character) = characters.next() {
 | 
			
		||||
    let value = match character {
 | 
			
		||||
      'I' => 1,
 | 
			
		||||
      'V' => 5,
 | 
			
		||||
      'X' => 10,
 | 
			
		||||
      'L' => 50,
 | 
			
		||||
      'C' => 100,
 | 
			
		||||
      'D' => 500,
 | 
			
		||||
      'M' => 1000,
 | 
			
		||||
      _ => panic!("Unknown character: {character}"),
 | 
			
		||||
    };
 | 
			
		||||
 | 
			
		||||
    if let Some(next) = characters.peek() {
 | 
			
		||||
      let subtract = match next {
 | 
			
		||||
        'V' | 'X' if character == 'I' => true,
 | 
			
		||||
        'L' | 'C' if character == 'X' => true,
 | 
			
		||||
        'D' | 'M' if character == 'C' => true,
 | 
			
		||||
        _ => false,
 | 
			
		||||
      };
 | 
			
		||||
 | 
			
		||||
      if subtract {
 | 
			
		||||
        number -= value;
 | 
			
		||||
        continue;
 | 
			
		||||
      }
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    number += value;
 | 
			
		||||
  }
 | 
			
		||||
 | 
			
		||||
  number
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
#[test]
 | 
			
		||||
fn test_roman_to_integer() {
 | 
			
		||||
  assert_eq!(roman_to_int("III".to_string()), 3);
 | 
			
		||||
  assert_eq!(roman_to_int("LVIII".to_string()), 58);
 | 
			
		||||
  assert_eq!(roman_to_int("MCMXCIV".to_string()), 1994);
 | 
			
		||||
  assert_eq!(roman_to_int("XX".to_string()), 20);
 | 
			
		||||
  assert_eq!(roman_to_int("DCXXI".to_string()), 621);
 | 
			
		||||
}
 | 
			
		||||
		Loading…
	
		Reference in New Issue