给定一个数字,我们需要使用递归来找到其数字的总和。
例子:
Input : 12345
Output : 15
Input : 45632
Output :20
分步执行的过程,可以更好地了解算法的工作原理。
设数字为12345。
步骤1-> 12345%10,等于-5 +(将12345/10发送到下一步)
步骤2-> 1234%10等于-4 +(将1234/10发送到下一步)
步骤3-> 123%10等于-3 +(将123/10发送到下一步)
步骤4-> 12%10等于-2 +(发送12/10到下一步)
步骤5-> 1%10等于-1 +(将1/10发送到下一步)
步骤6-> 0算法停止
下图将说明递归的过程
C++
// Recursive C++ program to find sum of digits
// of a number
#include
using namespace std;
// Function to check sum of digit using recursion
int sum_of_digit(int n)
{
if (n == 0)
return 0;
return (n % 10 + sum_of_digit(n / 10));
}
// Driven code
int main()
{
int num = 12345;
int result = sum_of_digit(num);
cout << "Sum of digits in "<< num
<<" is "<
C
// Recursive C program to find sum of digits
// of a number
#include
// Function to check sum of digit using recursion
int sum_of_digit(int n)
{
if (n == 0)
return 0;
return (n % 10 + sum_of_digit(n / 10));
}
// Driven Program to check above
int main()
{
int num = 12345;
int result = sum_of_digit(num);
printf("Sum of digits in %d is %d\n", num, result);
return 0;
}
Java
// Recursive java program to
// find sum of digits of a number
import java.io.*;
class sum_of_digits
{
// Function to check sum
// of digit using recursion
static int sum_of_digit(int n)
{
if (n == 0)
return 0;
return (n % 10 + sum_of_digit(n / 10));
}
// Driven Program to check above
public static void main(String args[])
{
int num = 12345;
int result = sum_of_digit(num);
System.out.println("Sum of digits in " +
num + " is " + result);
}
}
// This code is contributed by Anshika Goyal.
Python3
# Recursive Python3 program to
# find sum of digits of a number
# Function to check sum of
# digit using recursion
def sum_of_digit( n ):
if n == 0:
return 0
return (n % 10 + sum_of_digit(int(n / 10)))
# Driven code to check above
num = 12345
result = sum_of_digit(num)
print("Sum of digits in",num,"is", result)
# This code is contributed by "Sharad_Bhardwaj".
C#
// Recursive C# program to
// find sum of digits of a number
using System;
class GFG {
// Function to check sum
// of digit using recursion
static int sum_of_digit(int n)
{
if (n == 0)
return 0;
return (n % 10 + sum_of_digit(n / 10));
}
// Driven Program to check above
public static void Main()
{
int num = 12345;
int result = sum_of_digit(num);
Console.WriteLine("Sum of digits in " +
num + " is " + result);
}
}
// This code is contributed by Anant Agarwal.
PHP
输出:
Sum of digits in 12345 is 15