UVa 1586 - Molar Mass

       这道题一看感觉挺难,因为描述文字长篇大论,仔细读一读其实就是求相对分子质量。字符串处理。不过先来想偷懒用正则表达式,但是想了半天没有什么太好的方法。于是用普通的方法AC了。如果有大神有正则表达式的好方法留言一下,我也好学习学习。

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main1586 {

	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		int n = scan.nextInt();
		while(n-- > 0) {
			String str = scan.next();
			double mass = 0;
			for(int i=0; i<str.length(); i++) {
				char ch = str.charAt(i);
				if(ch>='C' && ch<='O') {
					if(ch == 'C') {
						int cnt = 0;
						int flag = 0;
						for(int j=i+1; j<str.length(); j++) {
							if(str.charAt(j)>='0' && str.charAt(j)<='9') {
								cnt = cnt * 10 + (int)(str.charAt(j) - '0');
								flag ++;
							}
							else break;
						}
						if(flag != 0)
						    mass += (double)cnt * 12.01;
						else
							mass += 12.01;
					}
					if(ch == 'H') {
						int cnt = 0;
						int flag = 0;
						for(int j=i+1; j<str.length(); j++) {
							if(str.charAt(j)>='0' && str.charAt(j)<='9') {
								cnt = cnt * 10 + (int)(str.charAt(j) - '0');
								flag ++;
							}
							else break;
						}
						if(flag != 0)
						    mass += (double)cnt * 1.008;
						else
							mass += 1.008;
					}
					if(ch == 'O') {
						int cnt = 0;
						int flag = 0;
						for(int j=i+1; j<str.length(); j++) {
							if(str.charAt(j)>='0' && str.charAt(j)<='9') {
								cnt = cnt * 10 + (int)(str.charAt(j) - '0');
								flag ++;
							}
							else break;
						}
						if(flag != 0)
						    mass += (double)cnt * 16.00;
						else
							mass += 16.00;
					}
					if(ch == 'N') {
						int cnt = 0;
						int flag = 0;
						for(int j=i+1; j<str.length(); j++) {
							if(str.charAt(j)>='0' && str.charAt(j)<='9') {
								cnt = cnt * 10 + (int)(str.charAt(j) - '0');
								flag ++;
							}
							else break;
							
						}
						if(flag != 0)
						    mass += (double)cnt * 14.01;
						else
							mass += 14.01;
					}
				}
			}
			System.out.printf("%.3f\n", mass);
		
		}

	}

}
posted @ 2014-12-24 22:33  Pickle  阅读(303)  评论(0编辑  收藏  举报