【PAT甲级 TreeMap的使用】1002 A+B for Polynomials (25 分) Java版 6/6通过
生活随笔
收集整理的這篇文章主要介紹了
【PAT甲级 TreeMap的使用】1002 A+B for Polynomials (25 分) Java版 6/6通过
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目
坑 & 心得
- 注意系數保留一位小數,次數是整數
- 當系數是0的時候,不要輸出。(最后一個測試點)
- 行末不要有多余空格,可以通過StringBuilder的deleteCharAt(sb.length() - 1);方式解決;不放心/怕誤刪的話,可以檢測StringBuilder末尾是否為空格,如果是,再刪除
通過以下測試用例,題目基本就沒問題了
測試點1:題目給的例子
2 1 2.4 0 3.2
2 2 1.5 1 0.5
答案:3 2 1.5 1 2.9 0 3.2
測試點2:易錯保留小數位數
3 5 5.66 4 5.22 4 1.2555
2 8 999 555 255.366666
答案:4 555 255.4 8 999.0 5 5.7 4 6.5
測試點3:系數為0不輸出
1 0 0
1 0 0
答案:0
一些小技巧
用空格分割字符串,把字符串變成數組
Scanner sc = new Scanner(System.in); String l1 = sc.nextLine(); String[] s1 = l1.split(" ");巧妙使用insert(index, String)逆序輸出TreeMap
for (Integer i_num : p.keySet()) {DecimalFormat df = new DecimalFormat("#0.0");sb.insert(0, i_num.toString() + " " + df.format((p.get(i_num))) + " ");// descending}使用DecimalFormat保留一位小數
DecimalFormat df = new DecimalFormat("#0.0"); df.format(num)去掉多余的空格
if (sb.length() > 0)// NO extra spacesb.deleteCharAt(sb.length() - 1);運行結果
全部測試用例通過
代碼
package cn.hanquan.test;import java.text.DecimalFormat; import java.util.Map; import java.util.Scanner; import java.util.Set; import java.util.TreeMap;public class Main {static TreeMap<Integer, Double> p = new TreeMap<>();public static void main(String[] args) {// inputScanner sc = new Scanner(System.in);String l1 = sc.nextLine();String l2 = sc.nextLine();sc.close();// convert to arrayString[] s1 = l1.split(" ");String[] s2 = l2.split(" ");int size1 = 2 * Integer.valueOf(s1[0]);int size2 = 2 * Integer.valueOf(s2[0]);for (int i = 1; i < size1; i += 2) {myPut(Integer.valueOf(s1[i]), Double.valueOf(s1[i + 1]));}for (int i = 1; i < size2; i += 2) {myPut(Integer.valueOf(s2[i]), Double.valueOf(s2[i + 1]));}// outputint count = 0;StringBuilder sb = new StringBuilder();for (Integer i_num : p.keySet()) {DecimalFormat df = new DecimalFormat("#0.0");if (p.get(i_num) == 0)// do not output 0continue;sb.insert(0, i_num.toString() + " " + df.format((p.get(i_num))) + " ");// descendingcount++;}sb.insert(0, count + " ");if (sb.length() > 0)// NO extra spacesb.deleteCharAt(sb.length() - 1);System.out.println(sb);}public static void myPut(int i_num, double d_num) {if (p.get(i_num) != null) {// existsp.put(i_num, d_num + p.get(i_num));} else {// not existsp.put(i_num, d_num);}} }總結
以上是生活随笔為你收集整理的【PAT甲级 TreeMap的使用】1002 A+B for Polynomials (25 分) Java版 6/6通过的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【Java TreeMap】测试Tree
- 下一篇: 【Java音频操作】调用有道词典语音接口