AOJ : 2188 - 単位変換器 (Unit Converter)
問題概要
http://rose.u-aizu.ac.jp/onlinejudge/ProblemSet/description.jsp?id=2188
日本語の問題文なので, 説明は省略します.
アルゴリズム
実装するだけです.
入力時の小数点の位置から, 指数表記した時の小数点の位置まで, いくら移動したかを求められれば解けます.
プログラム
public class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); HashMap<String,Integer> map = new HashMap<String,Integer>(); map.put("yotta",24); ... 省略 map.put("yocto",-24); while(n-- > 0){ String s = sc.next(); String a = sc.next(); String b = null; if(!sc.hasNextDouble()){ b = sc.next(); } else{ b = a; a = null; } //指数表記の生成 int idx = 0; for(;s.charAt(idx)=='0' || s.charAt(idx)=='.';idx++); String ns = "" + s.charAt(idx++); if(idx < s.length()){ ns += "."; for(;idx<s.length();idx++){ char ch = s.charAt(idx); ns += ch == '.' ? "" : ch; } } //指数表記前と後の小数点の位置を求める int before = 0; for(;before<s.length() && s.charAt(before)!='.';before++); if(before == s.length()) before--; int after = 0; for(;after<ns.length() && ns.charAt(after)!='.';after++); if(after == ns.length()) after--; int p = (a==null ? 0 : map.get(a)) + (ns.length() - after) - (s.length() - before); System.out.println(ns + " * 10^" + p + " " + b); } } }