Binary digits
Hi all,
I need to transform a list of numbers in binary digits and then I must find the way to analyze each bit, so that "0" gives me something and "1" gives me something else.
For example: 6 --> 110. First I analyze "1", then the other "1" and last the "0" in recursive way. I hope I've been clear. Could anyone suggest me the package i can use for this purpose?
Thanks a lot
[405 byte] By [
Gorditoa] at [2007-10-1 10:30:32]

public class Bitsy {
public static void main(String[] args) {
String testNumber = "6";
String binaryNumber = Integer.toString(Integer.parseInt(testNumber), 2);
for(int i = 0; i < binaryNumber.length(); i++) {
char ch = binaryNumber.charAt(i);
if(ch == '0') {
// Do something for 0 bit
} else if(ch == '1') {
// Do something for 1 bit
}
}
}
}
Here is the algorithm. It is not only recursive, it's tail recursive!. I am assuming your number n >0, otherwise there are zero bits.
First find q the largest power of two that is smaller than or equal to your number n. Say n =6, then q = 4.
Then:
private void recursive(int n, int q) {
assert n>=0 && q>=1;
if ( n >= q ) {
//do your 1 stuff
if (q > 1) recursive(n-q, q/2);
} else {
//do your 0 stuff
if (q > 1) recursive(n, q/2);
}
}
> > Sorry xHacker but the OP specifically asked for a
> > recursive solution.
> >
> > :-)
>
> **** it! I should have read the post properly. Thanks
> sabre150 :-)
Of course that requirement suggests that it is nothing more than a homework problem.
> > **** it! I should have read the post properly.
> Thanks
> > sabre150 :-)
>
> Of course that requirement suggests that it is
> nothing more than a homework problem.
Which makes me feel even bad... I could have suggested rentacoder.com :-)