Golang程序使用递归找到一个给定数字的倒数

如何在Golang中使用递归找到一个给定数字的倒数

在本教程中,我们将学习如何在Golang编程语言中找到给定数字的反向。如果我们想修改用For循环无法实现的函数,那么递归函数就比较合适。在这篇文章中,我们将通过使用递归来实现这一目标。

解释

迭代1。

Number = 54678
Reverse of number = 0
Reverse of number = Reverse of number * 10 + Number % 10
   = 0 + 54678 % 10
   = 0 + 8
   = 8
Number = Number / 10
   = 54678 / 10
   = 5467

迭代2。

Number = 5467
Reverse of number = 8
Reverse of number = Reverse of number * 10 + Number % 10
   = 8 * 10 + 5467 % 10
   = 80 + 7
   = 87
Number = Number / 10
   = 5467 / 10
   = 546

迭代3。

Number = 546
Reverse of number = 87
Reverse of number = Reverse of number * 10 + Number % 10
   = 87 * 10 + 546 % 10
   = 870 + 6
   = 876
Number = Number / 10
   = 546 / 10
   = 54

迭代4。

Number = 54
Reverse of number = 876
Reverse of number = Reverse of number * 10 + Number % 10
   = 876 * 10 + 54 % 10
   = 8760 + 4
   = 8764
Number = Number / 10
   = 54 / 10
   = 5

迭代5。

Number = 5
Reverse of number = 8764
Reverse of number = Reverse of number * 10 + Number % 10
   = 8764 * 10 + 5 % 10
   = 87640 + 5
   = 87645
Number = Number / 10
   = 5 / 10
   = 0

使用递归寻找一个数字的倒数

在这个例子中,我们要用递归的方法来寻找反向。我们在一个全局变量中存储数字的反向。

算法

  • 第1步 – 声明变量以存储实际数字和数字的反向。
  • 第2步 – 以数字为参数调用递归函数。

  • 第3步 – 打印结果。

示例

package main
import (

   // fmt package provides the function to print anything
   "fmt"
)

// declaring the variable to store the reverse of the number
var reverseOfNumberGlobal = 0
func reverse(number int) int {

   // returning if the number becomes zero
   if number == 0 {
      return 0
   }

   // finding reverse using mod and divide operator
   reverseOfNumberGlobal = reverseOfNumberGlobal*10 + (number % 10)

   // calling the function with a number as an argument
   reverse(number / 10)

   // returning the reverse
   return reverseOfNumberGlobal
}
func main() {

   // declaring the variable
   var number, reverseOfNumber int

   // initializing the variable
   number = 54678
   fmt.Println("Golang program to find the reverse of a number using a recursive function.")
   fmt.Printf("The number is %d. \n", number)

   // running for loop till the number becomes zero
   reverseOfNumber = reverse(number)

   // printing the result
   fmt.Printf("The reverse is %d. \n", reverseOfNumber)
}

输出

Golang program to find the reverse of a number using a recursive function.
The number is 54678.
The reverse is 87645.

结论

这就是我们如何在Golang中使用递归来找到一个数字的反向。递归调用的数量与数字的数量相等。要了解更多关于go的知识,你可以探索这些教程。