0

This is a follow up on the solutions in Find an integer not among four billion given ones since it's a old thread I created a new question. I wrote a bitset implementation assuming that the numbers are between java MAX_VALUE and MIN_VALUE integers. Here's the code

void bitsetWay() throws FileNotFoundException
    {
        String path=System.getProperty("user.dir")+"/src/com/sjcode/";
        Scanner in = new Scanner(new FileReader(path+"a.txt"));
        BitSet btpos= new BitSet(Integer.MAX_VALUE);
        BitSet btneg= new BitSet(Integer.MAX_VALUE);

        while(in.hasNextInt()){
            int n = in.nextInt();
            System.out.println(n);
            if (n<0)
            {
                btneg.set(-1*n);
            }
            else
            {
                btpos.set(n);
            }
        }
        System.out.println(btpos.nextClearBit(0) + " : " + btpos);
        //ignore btneg[0] since we treat 0 as +ve
        System.out.println(btneg.nextClearBit(1) + " : " + btneg);
    }

This works fine for this input in a.txt

1 
2 
2147483583
-2
-1 
0

-- Output:

3 : {0, 1, 2, 2147483583}
3 : {1, 2}

-- But when I give a number > 2147483583 it seems to wrap around and set bit 0! Am I missing something? Yes printing Integer.MAX_VALUE does print 2147483647!

Input:

1
2
2147483584
-2
-1
0

Output:

0 : {0, 1, 2, 2147483584}
3 : {1, 2}
Community
  • 1
  • 1
SidJ
  • 669
  • 12
  • 29

1 Answers1

1

I suspect it's a bug in your version of Java. I have Java 7 update 21 and it has a similar problem but not quite the same.

BitSet bs = new BitSet(Integer.MAX_VALUE);
bs.set(Integer.MAX_VALUE-1);
System.err.println(bs);
bs.set(Integer.MAX_VALUE);
System.err.println("Set ok but...");
System.out.println(bs);

prints

{2147483646}
Set ok but...
Exception in thread "main" java.lang.IndexOutOfBoundsException: fromIndex < 0: -2147483647
    at java.util.BitSet.nextSetBit(BitSet.java:701)
    at java.util.BitSet.toString(BitSet.java:1181)
    at java.lang.String.valueOf(String.java:2854)
    at java.io.PrintStream.println(PrintStream.java:821)
    at Main.main(Main.java:12)
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • Whoohoo I found a java bug! This is interesting since the IBM JDK is the standard at my (soon to be ex) workplace. – SidJ Jul 07 '13 at 17:03