문제

I need to Print all instances of a 32 bit binary number where there are no two 1s adjacent to each other.

For example:

10101010101010000000101010101010 is valid


01010101010110000000000000000000 is not because there are adjacent 1s

Here is what I have.

String number;
    boolean valid = false;


    for(int i = 0; i<= 1e32; i++)
    {
         //create binary number
         number = String.format("%32s", Integer.toBinaryString(i)).replace(' ', '0');

         for(int k = 0; k <= number.length() - 1; k++)
         { 
             //check if there are adjacent 1s
             if((number.charAt(k) == '1') && (number.charAt(k+1) == '1'))//I believe error is from this line
             {
                 valid = false;
             }
             else
             {
                 valid = true;
             }
         }
         if(valid == true)
         {
            //Print if there are no adjacent 1s
            System.out.println(number);
            valid = false;
         }
    }

This is the index error I receive. I believe the error is coming from when I check the indexes for adjacent 1s, but I cant figure out why it is out of bounds. Can anyone help?

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of    range: 32
at java.lang.String.charAt(String.java:658)
at program.program.main(program.java:30)
Java Result: 1
도움이 되었습니까?

해결책

Try using:

for(int k = 0; k < number.length() - 1; k++)

The line:

number.charAt(k+1)

will go out of bounds with your current setup, moving past the last element in the array.

다른 팁

When you check the kth element in your array, you are not checking to see if it is the end of the array before you check the k+1th element, which would take you out of bounds of your array.

So basically, you create a binary string from an integer, and want to see if it contains the substring "11". A simpler way to do this would be to search for that with regex or with

if(!number.contains("11"))
{
    System.out.println(number);
}

It's a little simpler, unless you are trying to get an algorithm down that proves it.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top