Multiply Two Numbers Without Using Arithmetic Operator in Java

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

在本节中,我们将学习如何在 Java 中不使用算术 运算符 (*) 来相乘两个数。

两个数的乘法可以通过重复加法方法来找到。这意味着将一个数(被乘数)加到自身,直到达到乘数次。如果我们想计算小数的乘法,可以使用此方法。

假设我们想计算 3 乘以 4,结果是12。这可以通过将 3 加四次来实现,即(3 + 3 + 3 + 3 = 12),或者将 4 加三次来实现,即(4 + 4 + 4 = 12)。两种方法结果相同。因此,我们可以使用递归来实现该逻辑。

使用 for 循环

MultiplicationExample1.java

输出

Enter the first number: 6
Enter the second number: 16
The multiplication of 6 and 16 is: 96

让我们看看相同的另一个逻辑。

MultiplicationExample2.java

输出

Enter the first number: 37
Enter the second number: 23
product of 37 and 23 is: 851

使用 while 循环

MultiplicationExample3.java

输出

Enter the multiplicand: 17
Enter the multiplicator: 8
The product of 17 and 8 is:  136

使用递归

通过使用递归,我们可以根据给定的约束来相乘两个整数。要相乘 a 和 b,请递归地将 a 加 b 次。

整数包括正数和负数。乘数或被乘数可能带有一个正号或负号。数字前没有符号表示正数。如果数字带有正号或负号,它们遵循下表中给出的规则。

Multiply Two Numbers Without Using Arithmetic Operator in Java

上表表示

  • 两个负数相乘得到一个正整数。
  • 两个正数相乘也得到一个正整数。
  • 一个正数和一个负数相乘得到一个负整数。
  • 一个负数和一个正数相乘得到一个负整数。

以下程序在数字为负数时也有效。

MultiplicationExample4.java

输出

The multiplication is: -45
The multiplication is: 136
The multiplication is: 144