一、题目描述
输入一个int型整数,按照从右向左的阅读顺序,返回一个不含重复数字的新的整数。
二、代码实现
1、暴力法
import java.util.Scanner;
public class Main {
//暴力法
public static void main4(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
String input = sc.next();
String str = input.substring(input.length()-1);
for (int i=input.length()-2; i>=0; i--) {
if (!str.contains(input.substring(i, i+1))) {
str += input.substring(i, i+1);
}
}
System.out.println(str);
}
}
}
2、使用与计数排序类似的思想
由于输出的数字字符总是在'0'-'9'之间,因此可以采用这种思想来解决重复的问题。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//int[] used = new int[10];
while (sc.hasNext()) {
//Arrays.fill(used, 0);
//
int[] used = new int[10];
int n = sc.nextInt();
int result = 0;
while (n != 0) {
//used[i] == 0表示数字字符i还没被使用
if (used[n%10] == 0) {
//used[n%10]++;也可以
used[n%10] = 1; //标记,下次遇到就跳过
result = result * 10 + n % 10;
}
n = n / 10;
}
System.out.println(result);
}
}
}
由于题目要求输出的是一个整数,所以,对于输入为123010,输出应该是132,而不是1032,或者0132。如果非要输出0132,那这里的输出必须是一个字符串,而不是一个整数。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
int[] used = new int[10];
int n = sc.nextInt();
int result = 0;
while (n != 0) {
//used[i] == 0表示数字字符i还没被使用
if (used[n%10] == 0) {
used[n%10] = 1; //标记,下次遇到就跳过
System.out.print(n%10);
}
n = n / 10;
}
}
}
}
比较繁琐但逻辑还算清晰的写法:
https://blog.nowcoder.net/n/3e64eba7f3724cd88cbd659b70632fe1?f=comment
3、使用Set
import java.util.Scanner;
import java.util.LinkedHashSet;
import java.util.Iterator;
public class Main {
//使用Set
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
int input = sc.nextInt();
LinkedHashSet<Integer> set = new LinkedHashSet<>();
while (input != 0) {
set.add(input % 10);
input /= 10;
}
/*
//Iterator<Integer> it = set.iterator<>();
Iterator it = set.iterator();
while (it.hasNext()) {
Object value = it.next();
System.out.print(value);
}
*/
//
for (Integer i : set) {
System.out.print(i);
}
System.out.println();
}
}
}
另一种写法:
import java.util.Scanner;
import java.util.HashSet;
public class Main {
//使用Set
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
int input = sc.nextInt();
HashSet<Integer> set = new HashSet<>();
while (input != 0) {
//由input%10控制从右到左输出(有HashSet无关,所以HashSet的插入无序性不影响);由HashSet控制是否已经输出过
if (set.add(input % 10)) { //当添加成功时,也就是之前没有输出过,才输出
System.out.print(input % 10);
}
input /= 10;
}
System.out.println();
}
}
}