Why is “i” in the for loop less than 63 instead of less than 62? I know the question says that inputs will be nonnegative and not completely 1s, but longs in java are signed, so if the representation is all 1s and positive, then the long will overflow, and it won’t ever hit the illegal argument exception. Aka, do we want the for loop to be checking the signed bit/is that the result that we are supposed to get?
5-4 for loop i < 63
I think < 63 is fine here since it only reaches to 62 eventually. If it is < 64, there might be problem as you described.
0 Likes
jrexthetrex
#3
Thanks for the response!
If I run the program with 9223372036854775807L, which is the max value of a long, should it hit the illegal argument exception? I get -4611686018427387905 back as the result instead of an illegal argument exception. Is this intended behavior?
Am I wrong in thinking that the 64th bit of a long is used as the signed bit?
0 Likes
Since Java Long.MAX is 2^63 - 1 so right shifting 63 you will find that two bits are different. However, if you use Java 8, which supports parsing unsigned long long value which will result exception as expected.
0 Likes