java笔试之提取不重复的整数

输入一个int型整数,按照从右向左的阅读顺序,返回一个不含重复数字的新的整数。

此题可以使用linkedHashedSetArrayListStack数组等来做。类似题目是输入一个数/字符串,从右往左输出,或者是输入一个数,删除重复数字输出等。

package test;

import java.awt.List;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Scanner;
import java.util.Stack;

/*
 * 题目描述
 * 输入一个int型整数,按照从右向左的阅读顺序,返回一个不含重复数字的新的整数。
 * */
public class exam18 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
            int num = scanner.nextInt();
            readOrder1(num);
            // readOrder2(num);
            // readOrder3(num);
            // readOrder4(num);
        }
        scanner.close();
    }

    public static void readOrder1(int num) {
        // 方法1:使用linkedhashset有序集合
        LinkedHashSet<Integer> set = new LinkedHashSet<Integer>();
        while (num != 0) {
            // 从右往左添加数到集合中
            set.add(num % 10);
            num /= 10;
        }
        // 使用迭代器,不知道下标
        Iterator iterator = set.iterator();
        while (iterator.hasNext()) {
            Object value = iterator.next();
            System.out.print(value);
        }

    }

    public static void readOrder2(int num) {
        // 使用arraylist查看list是否包含
        String str = String.valueOf(num);
        ArrayList list = new ArrayList();
        for (int i = str.length() - 1; i >= 0; i--) {
            char ch = str.charAt(i);
            if (!list.contains(ch)) {
                list.add(ch);
            }
        }
        for (int i = 0; i < list.size(); i++) {
            System.out.print(list.get(i));
        }
    }

    public static void readOrder3(int num) {
        // 方法3:使用一个下标标示0-9的整数数组,值作为存在标记
        StringBuilder sb = new StringBuilder();
        int[] arr = new int[10];
        while (num > 0) {
            int s = num % 10;
            if (arr[s] == 0) {
                arr[s] = 1;
                sb.append(s);
            }
            num /= 10;
        }
        System.out.println(sb.toString());
    }

    public static void readOrder4(int num) {
        // 方法4:使用栈
        Stack stack = new Stack();
        String str = String.valueOf(num);
        for (int i = str.length() - 1; i >= 0; i--) {
            char ch = str.charAt(i);
            if (!stack.isEmpty()) {
                if (!stack.contains(ch)) {
                    stack.add(ch);
                }
            } else {
                stack.push(ch);
            }
        }
        Iterator iterator = stack.iterator();
        while (iterator.hasNext()) {
            System.out.print(iterator.next());
        }
    }
}
原文地址:https://www.cnblogs.com/bella-young/p/6423487.html