使用递归在Java中返回给定数字的二进制对数。

huangapple go评论81阅读模式
英文:

Use recursion in Java to returns the binary logarithm of a given number

问题

以下是要翻译的内容:

这是我正在解决的问题的截图:


使用递归在Java中返回给定数字的二进制对数。


这是我的代码,它运行正常,但问题是如果 n <= 0,我想在同一个方法中返回 "未定义",但你可以看到我的方法返回类型是 int。那么我该怎么办?

public static void main(String[] args) {
    System.out.println(recursiveBinaryLog(1));
    System.out.println(recursiveBinaryLog(8));
    System.out.println(recursiveBinaryLog(0));
    System.out.println(recursiveBinaryLog(-2));
}

static int recursiveBinaryLog(int n) {
    if (n <= 0)
        return 0;
    else
        return (1 + recursiveBinaryLog(n / 2));
}
英文:

This is the Screenshot of The problem that i'm Solving:


使用递归在Java中返回给定数字的二进制对数。


This is my code, It's working fine but problem is If n<=0 i want to return "Undefined" at the same method But as you can see my method return type is int. So how can i do that?

public static void main(String[] args) {
    System.out.println(recursiveBinaryLog(1));
    System.out.println(recursiveBinaryLog(8));
    System.out.println(recursiveBinaryLog(0));
    System.out.println(recursiveBinaryLog(-2));
}

static int recursiveBinaryLog(int n) {
    if (n &lt;= 0)
        return 0;
    else
        return (1 + recursiveBinaryLog(n / 2));
}

答案1

得分: 2

要使方法 recursiveBinaryLog 返回一个 String 而不是一个 int,请在一个单独的方法中进行递归。

在链接的问题中没有说明 recursiveBinaryLog 方法本身必须是递归的,只是要求使用递归来解决问题,使用给定的算法。

static String recursiveBinaryLog(int n) {
	if (n <= 0)
		return "Undefined";
	return String.valueOf(recursiveBinaryLog0(n));
}

private static int recursiveBinaryLog0(int n) {
	return (n == 1 ? 0 : 1 + recursiveBinaryLog0(n / 2));
}
英文:

To have method recursiveBinaryLog return a String instead of an int, do the recursion in a separate method.

Nothing in the linked problem states that it is the recursiveBinaryLog method itself that has to be recursive, only that you have to use recursion to solve the problem, using the given algorithm.

static String recursiveBinaryLog(int n) {
	if (n &lt;= 0)
		return &quot;Undefined&quot;;
	return String.valueOf(recursiveBinaryLog0(n));
}

private static int recursiveBinaryLog0(int n) {
	return (n == 1 ? 0 : 1 + recursiveBinaryLog0(n / 2));
}

huangapple
  • 本文由 发表于 2020年8月4日 11:33:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/63239866.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定