简体   繁体   English

在Java中从十进制转换为二进制

[英]Converting From Decimal to Binary In Java

So I have code that will convert a decimal number to binary. 所以我有将十进制数转换为二进制的代码。 I use a recursive algorithm for it, however I cannot seem to get it to do what I want. 我为此使用了递归算法,但是似乎无法让它完成我想要的事情。 Here is the code: 这是代码:

import java.util.*;

public class binaryAddition {

    public static int toBinary(int a){


        int bin = 0;
        int remainder = 0;
        if(a >= 1){
            toBinary(a/2);
            bin = (a%2);
        }

        return bin;


    }

    public static void main(String[] args){

        System.out.println(toBinary(3));
        System.out.print(toBinary(3));
    }
}

So I want to to return the binary solution so that I can save it as a variable in my main method. 因此,我想返回二进制解决方案,以便可以将其另存为main方法中的变量。 However, my current output would only give me that last digit of the binary number. 但是,我当前的输出只会给我二进制数字的最后一位。 I used the number 3 just as a test case and I get 1 as an output for both print and println methods. 我将数字3用作测试用例,并获得1作为print和println方法的输出。 Why is that, and how can I fix it? 为什么会这样,我该如何解决?

Many Thanks! 非常感谢!

For a start, you might want to have toBinary return a String , not an int . 首先,您可能需要toBinary返回String ,而不是int Then you must use the result of it when you recurse. 然后,在递归时必须使用它的结果。 So you might write, inside your if , 因此,您可以在if写,

bin = toBinary(a / 2) + (a % 2);

assuming, of course, that toBinary returns String . 当然,假设toBinary返回String

If you don't do this, then you're just throwing away the result of your calculation. 如果您不这样做,那么您将丢弃计算结果。

The code is discarding the results of the recursive calls. 该代码将丢弃递归调用的结果。

Do something with the result of toBinary in the method. 在方法中使用toBinary的结果进行操作。

Just Do it Like i have Done . 就像我做完一样。

 public static void main(String[] args) 
{
    int n, count = 0, a;
    String x = "";
    Scanner s = new Scanner(System.in);
    System.out.print("Enter any decimal number:");
    n = s.nextInt();
    while(n > 0)
    {
        a = n % 2;
        if(a == 1)
        {
            count++;
        }
        x = x + "" + a;
        n = n / 2;
    }
    System.out.println("Binary number:"+x);
    System.out.println("No. of 1s:"+count);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM