Question

Write a recursive method in **pseudocode** that returns the number of 1’s in the binary representation...

Write a recursive method in **pseudocode** that returns the number of 1’s in the binary representation of N. Use the fact that this equal to the number of 1’s in the representation of N/2, plus 1, if N is odd

java pseudocode is best

0 0
Add a comment Improve this question Transcribed image text
Answer #1

JAVA CODE

import java.util.*;
public class Main
{
public static int rec(int n)
{
if(n==0)
return 0;
else if(n==1)
return 1;
else if(n%2==1)
return rec(n/2)+1;
else
return rec(n/2);
}
   public static void main(String[] args) {
   Scanner sc=new Scanner(System.in);
   int n=sc.nextInt();
   System.out.println(rec(n));
      
   }
}

EXPLANATION

  • If n==0,return 0
  • If n==1,return 1
  • If n is odd,return recursive call to method with n/2 plus 1
  • If n is even,return recursive call to method with n/2

Hope this helps

please comment if you need further clarification

Add a comment
Know the answer?
Add Answer to:
Write a recursive method in **pseudocode** that returns the number of 1’s in the binary representation...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT