I am trying to simply convert to Binary with recursion. I am having problems with the return statement. This compiles but give an overflow error when run. I don't know what to return (or if my statement is wrong) to prevent this error.
Thanks!
public static String convertToBinary(int number)
{
if(number > 0)
{
convertToBinary(number / 2);
convertToBinary((number % 2 ));
}
return convertToBinary((number));
}
int number
is already binary. Your question doesn't make sense - user207421 2017-02-14 22:38
Your problem was calling convertToBinary on both number/2 and number%2 I believe. This code works fine for me and isn't that different from what you had:
import java.util.Scanner;
public class DecToBin {
public static void main(String[] args) {
int input;
Scanner scan = new Scanner(System.in);
System.out.print("Enter number to convert to binary: ");
input = scan.nextInt();
convert(input);
}
public static void convert(int num) {
if (num>0) {
convert(num/2);
System.out.print(num%2 + " ");
}
}
}
Well, the problem seems to be that you're not actually doing anything in your recursive method.
In its most basic form your recursive method should contain:
(This is an oversimplified view, but it will do for now.)
The problem is that you're missing some escape conditions to handle the case of the parameter being a single bit long, that is when you can't subdivide it any more.
The other problem with your code is that you're not doing anything with the result of the recursive calls. You should store and concatenate them.
I suggest you start again: write a method that converts a single bit first (this will be non-recursive), then add the recursion to it. (A general advice: don't be afraid to throw away code and start again from scratch.)
Assuming this is homework I'll point out the main error..
return convertToBinary((number));
The return should return a value, not call a function. This will just adding a recursive state stacks which leads to your overflow. Try saving the values from your previous calls into a variable and returning that.
If this is not for homework, consider either: http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#toBinaryString%28int%29
or
http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#toString%28int,%20int%29
Once number
reaches zero, the method will simply call itself over and over again. The final return
needs to return something else - like a string. Having said that, I don't think this approach is terribly optimal.
number
is - Jesper 2012-04-05 18:09
Try below -:
public static String dec2Bin(int num) {
String result = ((num % 2 == 0) ? "0" : "1"); // expr
if (abs(num) > 1) {
result = dec2Bin(num / 2) + result;
}
return result;
}
This works but you have to print it from end
static void printBinary(int x){
if(x==0)System.out.printf("%3d", x);
else{
System.out.printf("%3d",x%2);
printBinary(x/2);
}
}
Following will work recursively. If number is negative it will add "-" as prefix to result.
void printBinary (int n) {
if (n < 0) { //base case
System.out.print("-");
printBinary(-n);
} else if (n < 2) { //base case
System.out.print(n);
return;
} else {
printBinary(n/2); //recursive step
int answer = n%2;
System.out.print(answer);
}
}
class DecBin {
static int convert(int i) {
if (i > 0) {
convert (i/2);
System.out.println(i%2);
return 0;
} else {
return 0;
}
}
public static void main(String[] args) {
DecBin.convert(10);
}
}
I tried to create a generic sub-routine which takes any Decimal integer & convert it to required BASE.
private Integer convertToBaseN(int num,int n, int pow)
{
Integer r = num%n;
if(num < n)
return new Double((Math.pow(10, pow-1))*r.doubleValue()).intValue();
return convertToBaseN(num/n, n,pow+1)+
new Double(Math.pow(10, pow-1)*r.doubleValue()).intValue();
}
num :- Decimal No you want to convert.
n:- Base to which you want to convert ( n =2 in your case).
pow = 1 (fixed);
Input=> convertToBaseN(503,5, 1); Output=> 4003
Input=> convertToBaseN(7,2, 1); Output=> 111
Caution:- It will not work for negative numbers.
Just add the binary conversion of (number/2*10) to the remainder of the number:
int binary(int dec) {
int remainder=dec%2;
if (dec==1 || dec==0)
return dec;
else
return remainder + (binary(dec/2)*10);
}
public class DecImalToBinary {
public static String decimalToBinary(int num){
StringBuilder sb= new StringBuilder();
if (num <2){
return ""+ num;
}
else{
return (sb.append(num%2)) + decimalToBinary((num/2));
}
}
public static void main(String[] args){
System.out.println(decimalToBinary(8));
}
}
public String convertirABinario(int n){
String b = "";
if (n == 0 || n == 1){
b = "" + n;
}
else{
b = b + convertirABinario(n/2) + n%2;
}
return b;
}
Here is my solution:
public static String binaerRec(int number)
{
if (number > 1)
{
return binaerRec(number / 2) + number % 2;
} else
{
return 1 + "";
}
}
have fun
Integer.parseInt()
already does the decimal to binary conversion. The rest of it is just a waste of time. However credit for being about the only answer so far that recognizes that the input can't be an int
- user207421 2017-02-14 22:48