/    Sign up×
Community /Pin to ProfileBookmark

recursion problem in java

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?????

to post a comment
Java

3 Comments(s)

Copy linkTweet thisAlerts:
@Khalid_AliMar 13.2006 — can u explain what is it the end goal here for this method?
Copy linkTweet thisAlerts:
@takkieMar 15.2006 — 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
Copy linkTweet thisAlerts:
@takkieMar 15.2006 — now that i look at your post again.... is this your homework assignment to write this recursively?

tak
×

Success!

Help @UAEU_Student spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.7,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...