如何在 Java 中查找整数的长度?

2025 年 5 月 13 日 | 阅读 6 分钟

在本节中,我们将学习 **查找 Java 中整数长度** 的不同方法。整数的长度表示该整数中存在的数字的总数。

我们可以通过以下方法找到整数的长度:

  • 使用 while 循环
  • 使用 String
  • 使用连续乘法
  • 使用对数
  • 使用递归

让我们一一讨论。

使用 while 循环

我们可以使用 while 循环来查找整数的长度。请观察以下代码。

文件名: IntegerLengthExample.java

输出

The length of the number 78 is 2
The length of the number 9 is 1
The length of the number 2345 is 4
The length of the number 899009 is 6
The length of the number 1 is 1
The length of the number 414 is 3
The length of the number 34 is 2
The length of the number 1000 is 4
The length of the number 2749 is 4

使用 String

另一种方法是将数字转换为字符串,然后计算其大小。字符串的大小即为字符串的长度。以下程序对此进行了说明。

文件名: IntegerLengthExample1.java

输出

The length of the number 78 is 2
The length of the number 9 is 1
The length of the number 2345 is 4
The length of the number 899009 is 6
The length of the number 1 is 1
The length of the number 414 is 3
The length of the number 34 is 2
The length of the number 1000 is 4
The length of the number 2749 is 4

使用连续乘法

我们可以将数字 1 乘以 10,直到它大于数字 n。每次乘以 10 时,我们将计数变量加 1。计数器的最终值即为整数 n 的长度。让我们通过以下程序来理解它。

文件名: IntegerLengthExample2.java

输出

The length of the number 78 is 2
The length of the number 9 is 1
The length of the number 2345 is 4
The length of the number 899009 is 6
The length of the number 1 is 1
The length of the number 414 is 3
The length of the number 34 is 2
The length of the number 1000 is 4
The length of the number 2749 is 4

使用对数

我们也可以使用 log 来查找整数的长度。请观察以下程序。

文件名: IntegerLengthExample3.java

输出

The length of the number 78 is 2
The length of the number 9 is 1
The length of the number 2345 is 4
The length of the number 899009 is 6
The length of the number 1 is 1
The length of the number 414 is 3
The length of the number 34 is 2
The length of the number 1000 is 4
The length of the number 2749 is 4

使用递归

我们也可以使用递归来找出整数的长度。以下程序对此进行了演示。

文件名: IntegerLengthExample4.java

输出

The length of the number 78 is 2
The length of the number 9 is 1
The length of the number 2345 is 4
The length of the number 899009 is 6
The length of the number 1 is 1
The length of the number 414 is 3
The length of the number 34 is 2
The length of the number 1000 is 4
The length of the number 2749 is 4