1

I am trying to figure out how I would take all the odd numbers in a file and convert them to binary 1 and the even numbers in the file and change them to binary 0. I am creating a binary search tree and I need to do the following for each element. - Decide if the element is even or odd, if even concatenate a 0 to my string, if odd concatenate a 1. -This will then build a binary String that represents a LONG -Then I want to convert the binary string to a long using these;

new BigInteger {myString}
longValue(); 

Heres an example of the file:

1973
3522
3465
1825
701
4842
2457
2895
746
4367

This is what Ive got so far. To find the odd and then the even #'s

public void convert (TreeNode<E> node){
    for(int i = 1; i <= size(); i++){
        if (i % 2 == 0){

        }
    }
    for(int i = 2; i <= size(); i++){
        if (i % 2 != 0){

        }
    }
}

So how would I convert the numbers to binary code and how would I convert the binary string to a long. Please anything will help Thanks!

CBH
  • 95
  • 1
  • 2
  • 9
  • Do you have an example of what its supposed to do? As it stands, its a bit unclear about what input you are getting and the intended output –  Nov 13 '13 at 16:53
  • Could you also please post what the input file will look like? While reading your description I had a vague understanding of what you want to do but based on the sample code you presented it seems my intuition may be mistaken. – Reuben Tanner Nov 13 '13 at 16:57
  • new BigInteger("1000").longValue(); and Long.valueOf("1000"); are equivalent. To get their binary values try something like - System.out.println(Long.toBinaryString((long) 1234)); - Also, you're binary string (in your example) seems to be a TreeNode. – Elliott Frisch Nov 13 '13 at 16:58

1 Answers1

2

Why not just create a string ?

public void convert (TreeNode<E> node){
    StringBuilder builder = new StringBuilder();
    for(int i = 1; i <= size(); i++){
        if (i % 2 == 0){
            builder.append("0");
        }
    }
    for(int i = 2; i <= size(); i++){
        if (i % 2 != 0){
            builder.append("1");
        }
    }
    String myBinaryString = builder.toString();
}

But why do you make two different loops ? And why the second one starts at 2 ? Is that normal you don't use node parameter ?

You could do this :

public void convert (TreeNode<E> node){
    StringBuilder builder = new StringBuilder();
    for(int i = 1; i <= size(); i++){
        if (i % 2 == 0){
            builder.append("0");
        }
        else{
            builder.append("1");
        }
    }
    String myBinaryString = builder.toString();
}
OlivierH
  • 3,875
  • 1
  • 19
  • 32
  • I was just building the string from what the OP said, he can do whatever he wants with the generated string after. And I don't know what size() method is, I reused the OP code. – OlivierH Nov 13 '13 at 17:04
  • @ElliottFrisch size() is how big the file is – CBH Nov 13 '13 at 17:06