Java 中對輸入數據進行倒序去重-常見兩種狀況處理

一、通常狀況下 默認第一次輸入數做爲 總的數目
輸入形如
5
12
21
32
11
12
這樣的數據處理


//
對輸入的數字去重並倒序輸出 public class testJava2 { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int len = scan.nextInt();//將第一次輸入的數據做爲循環次數 int[] numArr = new int[len]; int index = 0; for (int i = 0; i < len; i++) { numArr[i] = scan.nextInt(); } fun(numArr); } static void fun(int[] numArr){ // 排序 Arrays.sort(numArr); // 用List儲存結果 List<Integer> result = new ArrayList<Integer>(); result.add(numArr[0]); // for (int t = 1; t < numArr.length - 1; t++) { if (numArr[t] != numArr[t - 1]) { result.add(numArr[t]); } } // 處理數組中最後一位數字 if (numArr[numArr.length - 1] != numArr[numArr.length - 2]) { result.add(numArr[numArr.length - 1]); } // 輸出結果 for (int i = 0; i < result.size(); i++) { System.out.println(result.get(i)); } } }

 

二、考慮輸入時形如 -3322110 這樣的數據 要求 輸出 -123 即 末尾若是爲 0 則去掉,其餘位數據去重並倒序 數據 正負不變


public class testJava3 {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in); //
        String str = scan.nextLine();
        String tempStr = "";// 過渡字符
        String firstChar = "";// 首位字符
        String returnStr = "";// 最終輸出字符
        //
        if (str.charAt(0) == '-' || str.charAt(str.length() - 1) == '0') {
            // 首位處理
            if (str.charAt(0) == '-') {
                // System.out.println("首位處理");
                tempStr = str.substring(1, str.length());
                firstChar = str.substring(0, 1);// 取出首位
            }
            if (str.charAt(str.length() - 1) == '0') {
                // 末尾爲0處理
                tempStr = tempStr.substring(0, tempStr.length() - 1);
            }
        } else {
            tempStr = str;
        }
        // 去重處理
        List<String> list = new ArrayList<String>();
        for (int i = 0; i < tempStr.length(); i++) {
            // 此種判斷未考慮 123123 這種狀況
            // if (tempStr.charAt(i) != tempStr.charAt(i - 1))
            String n = String.valueOf(tempStr.charAt(i));
            if (!list.contains(n)) {
                list.add(n);
            }
        }
        // 反轉
        for (int i = list.size() - 1; i >= 0; i--) {
            returnStr += list.get(i);
        }
        // 輸出
        System.out.println(firstChar + returnStr);

    }
}
相關文章
相關標籤/搜索