tasks a-s
This commit is contained in:
parent
47bf37c096
commit
b83f433714
12433 changed files with 156208 additions and 123 deletions
37
Task/Roman-numerals-Decode/Java/roman-numerals-decode.java
Normal file
37
Task/Roman-numerals-Decode/Java/roman-numerals-decode.java
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
public class Roman {
|
||||
private static int decodeSingle(char letter) {
|
||||
switch(letter) {
|
||||
case 'M': return 1000;
|
||||
case 'D': return 500;
|
||||
case 'C': return 100;
|
||||
case 'L': return 50;
|
||||
case 'X': return 10;
|
||||
case 'V': return 5;
|
||||
case 'I': return 1;
|
||||
default: return 0;
|
||||
}
|
||||
}
|
||||
public static int decode(String roman) {
|
||||
int result = 0;
|
||||
String uRoman = roman.toUpperCase(); //case-insensitive
|
||||
for(int i = 0;i < uRoman.length() - 1;i++) {//loop over all but the last character
|
||||
//if this character has a lower value than the next character
|
||||
if (decodeSingle(uRoman.charAt(i)) < decodeSingle(uRoman.charAt(i+1))) {
|
||||
//subtract it
|
||||
result -= decodeSingle(uRoman.charAt(i));
|
||||
} else {
|
||||
//add it
|
||||
result += decodeSingle(uRoman.charAt(i));
|
||||
}
|
||||
}
|
||||
//decode the last character, which is always added
|
||||
result += decodeSingle(uRoman.charAt(uRoman.length()-1));
|
||||
return result;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
System.out.println(decode("MCMXC")); //1990
|
||||
System.out.println(decode("MMVIII")); //2008
|
||||
System.out.println(decode("MDCLXVI")); //1666
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue