I just started Data Structures and Algorithms which is taught in Java. So far I've only learned C++ in my life so I'm still VERY new to using java.
Anyways I have a homework problem I'm a little stuck on:
Write a recursive method that returns the number of 1's in the binary representation of N. Use the fact that this is equal to the number of 1's in the representation of N/2 + 1, if N is odd.
Now i'm not sure how exactly to do this. I already have a function set up that takes an integer and converts it to binary and stores it in a string, yet the rest I'm kinda lost on.
If I can get some guidance, that would really help.
This is what I have so far:
import java.io.*;
public class Homework1Code {
static void prtbinary(String Molly, int size){
if(size <=0){
return;
}
}
public static void main(String[] args) {
int i = 38;
String binstr = Integer.toBinaryString(i);
System.out.println("The Original Decimal Number is: " + binstr);
prtbinary(binstr, binstr.length());
}
}
Thanks
This is not a hard problem to solve. What you need to do is stop writing code and first solve the problem on paper. Then convert your algorithm to code.
Step one: think!
It is very hard to write a recursive method whose return type is void.
The question is about doing arithmetic, so leave the value as an int rather than convering to a string.
Then there are two facts (for non-negative numbers):
bitCount of 010101 is bitCount of 010101/2 = 01010 plus 1 bitCount of 010100 is bitCount of 010100/2 = 01010
Rinse and repeat until finished (induction).
Just don't look at the source to Integer.bitCount.
首先,将问题减少到最简单的情况下...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.