Created
May 11, 2013 21:30
-
-
Save chmllr/5561490 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.HashMap; | |
import java.util.Map; | |
import java.util.Scanner; | |
public class Mmass { | |
static Map<Character, Integer> m = new HashMap<Character, Integer>(); | |
public static void main(String[] args) { | |
m.put('H', 1); | |
m.put('C', 12); | |
m.put('O', 16); | |
String molecule = (new Scanner(System.in)).next(); | |
System.out.println(compute(molecule,0,0)); | |
} | |
private static int compute(String str, int pos, int acc) { | |
if (pos >= str.length()) return acc; | |
char c = str.charAt(pos); | |
int mass = 0; | |
if(c == '(') { | |
int brackets = 1; | |
StringBuffer tmp = new StringBuffer(); | |
while (brackets > 0) { | |
char x = str.charAt(++pos); | |
tmp.append(x); | |
if (x == '(') brackets++; | |
if (x == ')') brackets--; | |
} | |
tmp.deleteCharAt(tmp.length()-1); | |
mass = compute(tmp.toString(), 0, 0); | |
} | |
char n = pos < str.length()-1 ? str.charAt(++pos) : '1'; | |
boolean multiply = Character.isDigit(n); | |
if(multiply) pos++; | |
acc += (c == '(' ? mass : m.get(c)) * (multiply ? Character.getNumericValue(n) : 1); | |
return compute(str, pos, acc); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment