UVA 1586 分子量(簡單模擬計算)

思路,先判斷當前字符是不是數字,不是數字的話先記錄當前字符,然後向後查找直到下一個不是數字的字符出現。

import java.util.Scanner;

public class Main {
	public static void main(String[] args){
		Scanner scan = new Scanner(System.in);
		double[] A = {12.01,1.008,16.00,14.01};
		int n = scan.nextInt();
		while(n--!=0){
			String s = scan.next();
			int i = 0;
			double ans = 0;
			while(i<s.length()){
				char c = s.charAt(i);
				i++;
				if(!(c>='0'&&c<='9')){
					String str = "";
					while(i<s.length()&&s.charAt(i)>='0'&&s.charAt(i)<='9'){
						str+=s.charAt(i);
						i++;
					}
					if(str.equals(""))
						str = "1";
					int num = Integer.valueOf(str);
					if(c=='C'){
						ans += A[0]*num;
					}else if(c=='H'){
						ans += A[1]*num;
					}else if(c=='O'){
						ans += A[2]*num;
					}else{
						ans += A[3]*num;
					}
				}
			}
			System.out.printf("%.3f\n",ans);
		}
	}
	
	
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章