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); } } }
作者:Pickle
声明:对于转载分享我是没有意见的,出于对博客园社区和作者的尊重一定要保留原文地址哈。
致读者:坚持写博客不容易,写高质量博客更难,我也在不断的学习和进步,希望和所有同路人一道用技术来改变生活。觉得有点用就点个赞哈。
![](https://images2015.cnblogs.com/blog/735119/201701/735119-20170111112835275-168981902.gif)
![](https://images2015.cnblogs.com/blog/735119/201701/735119-20170111112841431-2047172832.jpg)
![](https://images2015.cnblogs.com/blog/735119/201701/735119-20170111112847494-1544911856.jpg)
![](https://images2015.cnblogs.com/blog/735119/201701/735119-20170111112904385-918783221.jpg)
![](https://images2015.cnblogs.com/blog/735119/201701/735119-20170111120143119-1302805212.jpg)
![](https://images2015.cnblogs.com/blog/735119/201701/735119-20170111112856369-1466718103.jpg)
![](https://images2015.cnblogs.com/blog/735119/201701/735119-20170111112830416-794416355.jpg)
![](https://images2015.cnblogs.com/blog/735119/201701/735119-20170111113919510-1155220901.gif)