📜  递归练习问题套装2

📅  最后修改于: 2021-05-06 17:55:32             🧑  作者: Mango

解释以下功能的功能。

问题1

C++
/* Assume that n is greater than or equal to 1 */
int fun1(int n)
{
if(n == 1)
    return 0;
else
    return 1 + fun1(n/2);
}
 
// This code is contributed by shubhamsingh10


C
/* Assume that n is greater than or equal to 1 */
int fun1(int n)
{
  if(n == 1)
     return 0;
  else
     return 1 + fun1(n/2);
}


Java
/* Assume that n is greater than or equal to 1 */
static int fun1(int n)
{
if(n == 1)
    return 0;
else
    return 1 + fun1(n/2);
}
 
// This code is contributed by shubhamsingh10


Python3
# Assume that n is greater than or equal to 1 */
def fun1(n):
    if(n == 1):
        return 0
    else:
        return 1 + fun1(n/2)
 
# This code is contributed by shubhamsingh10


C#
/* Assume that n is greater than or equal to 1 */
static int fun1(int n)
{
if(n == 1)
    return 0;
else
    return 1 + fun1(n/2);
}
 
// This code is contributed by shubhamsingh10


Javascript


C++
/* Assume that n is greater than or equal to 0 */
void fun2(int n)
{
if(n == 0)
    return;
 
fun2(n/2);
cout << n%2 << endl;
}
 
//This code is contributed by shubhamsingh10


C
/* Assume that n is greater than or equal to 0 */
void fun2(int n)
{
  if(n == 0)
    return;
 
  fun2(n/2);
  printf("%d", n%2);
}


Java
/* Assume that n is greater than or equal to 1 */
static void fun2(int n)
{
if(n == 0)
    return;
  
fun2(n/2);
System.out.println(n%2);
}
 
// This code is contributed by Shubhamsingh10


Python3
# Assume that n is greater than or equal to 0 */
def fun2(n):
    if(n == 0):
        return
     
    fun2(n / 2)
    print(n % 2, end="")
 
# This code is contributed by shubhamsingh10


C#
void fun2(int n)
{
if(n == 0)
    return;
   
fun2(n/2);
Console.Write(n%2);
}
// This code is contributed by shubhamsingh10


Javascript


答:函数计算并返回

log2floor

。例如,如果n在8到15之间,则fun1()返回3。如果n在16到31之间,则fun1()返回4。
问题2

C++

/* Assume that n is greater than or equal to 0 */
void fun2(int n)
{
if(n == 0)
    return;
 
fun2(n/2);
cout << n%2 << endl;
}
 
//This code is contributed by shubhamsingh10

C

/* Assume that n is greater than or equal to 0 */
void fun2(int n)
{
  if(n == 0)
    return;
 
  fun2(n/2);
  printf("%d", n%2);
} 

Java

/* Assume that n is greater than or equal to 1 */
static void fun2(int n)
{
if(n == 0)
    return;
  
fun2(n/2);
System.out.println(n%2);
}
 
// This code is contributed by Shubhamsingh10

Python3

# Assume that n is greater than or equal to 0 */
def fun2(n):
    if(n == 0):
        return
     
    fun2(n / 2)
    print(n % 2, end="")
 
# This code is contributed by shubhamsingh10

C#

void fun2(int n)
{
if(n == 0)
    return;
   
fun2(n/2);
Console.Write(n%2);
}
// This code is contributed by shubhamsingh10

Java脚本