使用递归查找整数的二进制等效项的 C# 程序
给定一个整数,现在我们使用递归将给定的整数转换为二进制数。递归是一种函数直接或间接调用自身的方法,这种类型的函数称为递归函数。它非常有效地解决了这个问题,就像我们找到整数的二进制等价物一样。
例子:
Input : 10
Output: 1010
Input : 11
Output: 1011
方法:
To display the binary equivalent of an integer we use the following steps:
- If condition is used to check if the given value is not equal to zero.
- If the given condition is true then perform the modulus of the val by 2, then add the modulus result to 10 and then multiply the value of the result with the value of decimaltobinary() function.
- Now repeat step 2 until the value of val variable is greater than zero.
- Print the array in reverse order now.
- And if the condition is false then it will execute the else section, i.e., return 0
下图可以帮助您更好地理解该方法。
让我们考虑整数是 10。现在我们找到 10 的二进制等价物,所以,
- 10 % 2 + 10 * (10 / 2) % 2 将返回 0
- 5 % 2 + 10 * (5 / 2) % 2 将返回 1
- 2 % 2 + 10 * (2 / 2) % 2 将返回 0
- 1 % 2 + 10 * (1 / 2) % 2 将返回 1
所以最终结果是1010。
示例 1:
C#
// C# program to display the binary equivalent
// of an integer
using System;
class GFG{
// Driver code
public static void Main(string[] args)
{
// Input
int num = 15;
decimaltobinary(num);
}
// Function to display the binary equivalent
// of an integer
public static int decimaltobinary(int val)
{
int binary;
if (val != 0)
{
binary = (val % 2) + 10 * decimaltobinary(val / 2);
Console.Write(binary);
return 0;
}
else
{
return 0;
}
}
}
C#
// C# program to display the binary equivalent
// of an integer
using System;
class GFG{
// Function to display the binary equivalent
// of an integer
public static int decimaltobinary(int val)
{
int binary;
if (val != 0)
{
binary = (val % 2) + 10 * decimaltobinary(val / 2);
Console.Write(binary);
return 0;
}
else
{
return 0;
}
}
// Driver code
public static void Main(string[] args)
{
int num;
// Reading input from user
Console.Write("Hi! Enter the number:");
num = int.Parse(Console.ReadLine());
decimaltobinary(num);
}
}
输出
1111
示例 2:
C#
// C# program to display the binary equivalent
// of an integer
using System;
class GFG{
// Function to display the binary equivalent
// of an integer
public static int decimaltobinary(int val)
{
int binary;
if (val != 0)
{
binary = (val % 2) + 10 * decimaltobinary(val / 2);
Console.Write(binary);
return 0;
}
else
{
return 0;
}
}
// Driver code
public static void Main(string[] args)
{
int num;
// Reading input from user
Console.Write("Hi! Enter the number:");
num = int.Parse(Console.ReadLine());
decimaltobinary(num);
}
}
输出:
Hi! Enter the number:10
1010