HarshJain
Newbie
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:
So I want to return the binary solution so that I can save it as a variable in my main method. However, my current output would only give me that last digit of the binary number. I utilized the number 3 similarly as an experiment and I get 1 as a result for both print and println techniques. Why would that be, and how might I fix it?
Before trying this code I have done several research on the web and read a couple of articles on binary to decimal in java to understand the concept in a better way, my source of Information is Wiki, scaler, and GFG.
Much obliged!
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 return the binary solution so that I can save it as a variable in my main method. However, my current output would only give me that last digit of the binary number. I utilized the number 3 similarly as an experiment and I get 1 as a result for both print and println techniques. Why would that be, and how might I fix it?
Before trying this code I have done several research on the web and read a couple of articles on binary to decimal in java to understand the concept in a better way, my source of Information is Wiki, scaler, and GFG.
Much obliged!