John OConnor John OConnor - 2 months ago 15
Java Question

Binary to String - Error on large numbers .StringIndexOutOfBounds

I am doing some online coding projects trying to learn to program and advanced my skills. The object of the current project is to figure out in binary which base 2 number matches with the other number first. Im probably not explaining that correctly.

For example, if I had my binary strings as 10010 and 10011 the answer would be 2 but if I had 11111 and 10000, the answer would be 16. My code below works for the first 4 tests it runs, but on the fifth test, it throws a .StringIndexOutOfBounds - the sample data on the last test being passed to my method is n = 1073741824 & m = 1006895103. Im assuming it may be an issue regarding size or limitations of charAt() but not quite sure... any suggestions would be greatly appreciated. Code Below:

int equalPairOfBits(int n, int m) {
String theN = Integer.toBinaryString(n);
String theM = Integer.toBinaryString(m);
int pos = 0;
int nLen = theN.length();
int mLen = theN.length();
char[] nArray = new char[nLen];
char[] mArray = new char[mLen];

for(int i = nLen - 1; i > -1; i--){
nArray[i] = theN.charAt(i);
}
for(int i = mLen - 1; i > -1; i--){
mArray[i] = theM.charAt(i);
}
boolean isSame = false;
for(int i = nLen - 1; i > -1; i--){
if(nArray[i] == mArray[i] && isSame == false)
{
pos = i;
isSame = true;
}

}
pos = nLen - pos;
int mult = 1;
for(int i = 1; i < pos; i++){
if(pos == 0)
mult = 1;
else
mult = mult * 2;
}
return mult;
}


The Error I Am Getting:

Exception in thread "main" java.lang.AssertionError: java.lang.reflect.InvocationTargetException
at myCode._invoke(file.java on line ?)
at myCode.main(file.java on line ?)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at myCode._invoke(file.java on line ?)
... 1 more
Caused by: java.lang.ArrayIndexOutOfBoundsException: 30
at _runppnqw.equalPairOfBits(file.java on line 18)

Answer

your problem is here

int mLen = theN.length(); should use theM

if the length of theM String is smaller than theN you will get the index out of bounds exception when you iterate past the length of theM string