英文:
Use recursion in Java to returns the binary logarithm of a given number
问题
以下是要翻译的内容:
这是我正在解决的问题的截图:
这是我的代码,它运行正常,但问题是如果 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:
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 <= 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 <= 0)
return "Undefined";
return String.valueOf(recursiveBinaryLog0(n));
}
private static int recursiveBinaryLog0(int n) {
return (n == 1 ? 0 : 1 + recursiveBinaryLog0(n / 2));
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论