java 仅使用递归(无循环)在java中二进制到十进制
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28052626/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Binary to decimal in java using only recursion (no loops)
提问by KangarooRIOT
I can not seem to get my method to convert the binary number to a decimal correctly. I believe i am really close and in fact i want to use a string to hold the binary number to hold it and then re-write my method to just use a .length to get the size but i do not know how to actually do that. Could someone help me figure out how i'd rewrite the code using a string to hold the binary value and then obtain the decimal value using only recursion and no loops?
我似乎无法获得将二进制数正确转换为十进制数的方法。我相信我真的很接近,事实上我想使用一个字符串来保存二进制数来保存它,然后重新编写我的方法以仅使用 .length 来获取大小,但我不知道如何实际做到这一点. 有人可以帮我弄清楚如何使用字符串重写代码来保存二进制值,然后仅使用递归而不使用循环来获取十进制值吗?
This is my full code right now and i won't get get rid of asking for the size of the binary and use a string to figure it out myself. Please help :)
这是我现在的完整代码,我不会摆脱询问二进制文件的大小并使用字符串自己计算出来的。请帮忙 :)
package hw_1;
import java.util.Scanner;
public class Hw_1 {
public static void main(String[] args) {
int input;
int size;
Scanner scan = new Scanner(System.in);
System.out.print("Enter decimal integer: ");
input = scan.nextInt();
convert(input);
System.out.println();
System.out.print("Enter binary integer and size : ");
input = scan.nextInt();
size = scan.nextInt();
System.out.println(binaryToDecimal(input, size));
}
public static void convert(int num) {
if (num > 0) {
convert(num / 2);
System.out.print(num % 2 + " ");
}
}
public static int binaryToDecimal(int binary, int size) {
if (binary == 0) {
return 0;
}
return binary % 10
* (int) Math.pow(2, size) + binaryToDecimal((int) binary / 10, size - 1);
}
}
回答by MaxZoom
Here is an improved version
这是一个改进的版本
package hw_1;
import java.util.Scanner;
public class Hw_1 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter decimal integer : ");
int input = scan.nextInt();
convert(input);
System.out.println();
System.out.print("Enter binary integer : ");
String binInput = scan.next();
System.out.println(binaryToDecimal(binInput));
}
public static void convert(int num) {
if (num>0) {
convert(num/2);
System.out.print(num%2 + " ");
}
}
public static int binaryToDecimal(String binInput){
int len = binInput.length();
if (len == 0) return 0;
String now = binInput.substring(0,1);
String later = binInput.substring(1);
return Integer.parseInt(now) * (int)Math.pow(2, len-1) + binaryToDecimal(later);
}
}
回答by afzalex
Don't parse binary in reverse order.
Here by calling binaryToDecimal(int)
it will return decimal number.
不要以相反的顺序解析二进制文件。
这里通过调用binaryToDecimal(int)
它将返回十进制数。
public static int binaryToDecimal(int binary) {
return binaryToDecimal(binary, 0);
}
public static int binaryToDecimal(int binary, int k) {
if (binary == 0) {
return 0;
}
return (int) (binary % 10 * Math.pow(2, k) + binaryToDecimal(binary / 10, k + 1));
}
If you are coding just to convert numbers (not for practice). Then better approach would be to use Integer.parseInt(String, 2)
. Here you will have to pass binary number in the form of String
.
如果您编码只是为了转换数字(不是为了练习)。那么更好的方法是使用Integer.parseInt(String, 2)
. 在这里,您必须以String
.
回答by Mike Elofson
If you are looking to do this using a String
to hold the binary representation, you could use the following:
如果您希望使用 aString
来保存二进制表示来执行此操作,则可以使用以下内容:
public static int binaryToDecimal(String binaryString) {
int size = binaryString.length();
if (size == 1) {
return Integer.parseInt(binaryString);
} else {
return binaryToDecimal(binaryString.substring(1, size)) + Integer.parseInt(binaryString.substring(0, 1)) * (int) Math.pow(2, size - 1);
}
}
How this works, is with the following logic. If, the number you send it is just 1 character long, or you get to the end of your recursive work, you will return just that number. So for example, 1
in binary is 1
in decimal, so it would return 1
. That is what
这是如何工作的,遵循以下逻辑。如果您发送的数字只有 1 个字符长,或者您的递归工作已结束,您将只返回该数字。例如,1
二进制是1
十进制,所以它会返回1
. 那是什么
if (size == 1) {
return Integer.parseInt(binaryString);
}
Does. The second (and more important part) can be broken up into 2 sections. binaryString.substring(1, size)
and Integer.parseInt(binaryString.substring(0, 1)) * (int) Math.pow(2, size - 1)
. The call made in the return statement to
做。第二个(也是更重要的部分)可以分为 2 个部分。binaryString.substring(1, size)
和Integer.parseInt(binaryString.substring(0, 1)) * (int) Math.pow(2, size - 1)
。在 return 语句中调用
binaryString.substring(1, size)
Is made to pass all but the first number of the binary number back into the function for calculation. So for example, if you had 11001
, on the first loop it would chop the first 1
off and call the function again with 1001
. The second part, is adding to the total value whatever the value is of the position number at the head of the binary representation.
使除二进制数的第一个数字之外的所有数字都传递回函数进行计算。因此,例如,如果您有11001
,则在第一个循环中,它会将第一个1
关闭并再次使用 调用该函数1001
。第二部分,无论二进制表示开头的位置编号的值是什么,都将其添加到总值中。
Integer.parseInt(binaryString.substring(0, 1))
Gets the first number in the current string, and
获取当前字符串中的第一个数字,以及
* (int) Math.pow(2, size - 1)
is saying Multiple that by 2 to the power of x, where x is the position that the number is in
. So again with our example of 11001
, the first number 1
is in position 4
in the binary representation, so it is adding 1 * 2^4
to the running total.
是说Multiple that by 2 to the power of x, where x is the position that the number is in
。再次以我们的 为例11001
,第一个数字在二进制表示1
中就位4
,因此它添加1 * 2^4
到运行总数中。
If you need a method to test this, I verified it working with a simple main method:
如果你需要一种方法来测试这个,我用一个简单的 main 方法验证了它:
public static void main(String args[]) {
String binValue = "11001";
System.out.println(binaryToDecimal(binValue));
}
Hopefully this makes sense to you. Feel free to ask questions if you need more help.
希望这对你有意义。如果您需要更多帮助,请随时提出问题。
回答by Giorgi Tsiklauri
Here is the clean and concise recursive algorithm; however, you'll need to keep track of some global variable for power, and I have defined it as a static member.
这是干净简洁的递归算法;但是,您需要跟踪某些全局变量以获取电源,并且我已将其定义为静态成员。
static int pow = 0;
public static int binaryToDecimal(int binary) {
if (binary <= 1) {
int tmp = pow;
pow = 0;
return binary * (int) Math.pow(2, tmp);
} else {
return ((binary % 10) * (int) Math.pow(2, pow++)) + binaryToDecimal(binary / 10);
}
}
Note: the reason, why I introduce pow, is that static field needs to be reset.
注意:之所以引入pow,是因为需要重置静态字段。