Click to See Complete Forum and Search --> : recursion problem in java


UAEU_Student
03-13-2006, 02:14 PM
Hi guys,

Here is the method that I wrote to convert a number from binary to decimal.

public static void binary2decimal(int a){
String r=a+"";
double sum=0;
for(int i=0;i<r.length();i++){
if(r.charAt(i)=='1'){
double product=1;
for(int q=0;q<r.length()-i-1;q++){
product=product*2;}
sum=sum+product;}
else if(r.charAt(i)=='.'){
int pos=i+1;
while(r.charAt(pos)=='1'){
double prod=1;
for(int q=0;q<r.length()-pos-1;q++){
prod=prod*1/2;
pos++;
if(pos==r.length()-1){
break;}}
sum=sum+prod;}}}
System.out.println(sum);
}
//------------------------------------

How can I write it this method recursively?????

Khalid Ali
03-13-2006, 02:32 PM
can u explain what is it the end goal here for this method?

takkie
03-15-2006, 12:35 PM
if you are trying to come up with a more efficient, faster, shorter lines for a function that will convert binary to decimal.....

Instead of trying to figure out how to write it recursively, less line..etc... how about this?

Say your binary number is in a variable, myBinary

1 lines of code only to convert from bin to dec...

System.out.println(Integer.parseInt(String.valueOf(myBinary), 2));

voila... you get it in decimal...

-Tak

takkie
03-15-2006, 12:38 PM
now that i look at your post again.... is this your homework assignment to write this recursively?

tak