Unique Number in Java Program

2025年3月29日 | 阅读 4 分钟

如果一个正整数的各位数字没有重复,那么这个数字就是唯一的。换句话说,当且仅当数字不重复时,一个数字才被认为是唯一的。例如,20、56、9863、145 等是唯一数字,而 33、121、900、1010 等不是唯一数字。在本节中,我们将创建 Java 程序检查数字是否唯一。

Unique Number in Java Program

检查数字是否唯一的方法如下:

手动比较每个数字

检查数字是否唯一的步骤如下:

  1. 从用户那里读取一个数字。
  2. 找出数字的最后一位数字。
  3. 将数字的所有数字与最后一位数字进行比较。
  4. 如果数字出现不止一次,则该数字不是唯一的。
  5. 否则,删除数字的最后一位数字。
  6. 重复步骤 2 至 5,直到数字变为零。

UniqueNumberExample1.java

输出 1

Enter the number you want to check: 13895
The number is unique.

输出 2

Enter the number you want to check: 11100
The number is not unique.

输出 3

Enter the number you want to check: 10000
The number is not unique.

使用 String

使用 String,我们还可以检查数字是否唯一。我们使用 String 的 charAt() 方法来比较字符串的每个数字。

UniqueNumberExample2.java

输出 1

Enter the number you want to check: 9876
The number is unique.

输出 2

Enter the number you want to check: 1010
The number is not unique.

输出 3

Enter the number you want to check: 200
The number is not unique.

在上面的程序中,我们首先使用 toString() 方法将 number 变量转换为 String。之后,我们使用 length() 方法确定字符串的长度。

我们使用了两个 for 循环(内部和外部)来遍历数字。在 if 语句内部,对于每次迭代,我们使用 charAt() 方法比较数字。如果两个数字相同,则 break 语句会中断程序的执行并打印该数字不唯一,否则打印该数字是唯一的

使用数组

我们还可以使用数组来检查数字是否唯一。在此方法中,我们找出数字的所有数字并将其存储在数组中。之后,将所有索引的值相互比较。如果值相同,则该数字不是唯一的。请记住,在比较所有索引之前,我们需要声明数组的大小(数字的位数)。

UniqueNumberExample3.java

输出 1

Enter the number you want to check: 898
898 is not a unique number.

输出 2

Enter the number you want to check: 201
201 is a unique number.

输出 3

Enter the number you want to check: 700
700 is not a unique number.