Using what we would consider a natural base, such as 10
, leads to lots of operations. Have you ever multiplied two 9-digit numbers? Using a method that we typically learn in school, that would involve 81 digit multiplications. However, Java would use one multiply instruction.
What about large numbers, such as 18-digit numbers? For us, that would involve 324 digit multiplications. Here, the implementation would use 2 int
s, equivalent to multiplying 2-digit numbers for us. That would result in 4 multiplication instructions for Java.
Why not use a larger base in Java, to further reduce the number of operations? Because of multiplication. It is guaranteed that the result of multiplying two int
s in Java will fit in a long
, and 1 billion (10^9) is the largest power of 10 that fits in an int
. These operations are still very easy for Java - just multiply instructions. It is possible to use a somewhat larger number, such as 2 billion, or Integer.MAX_VALUE
(slightly over 2 billion), but that answer chose to use 1 billion, for human readability purposes. Anything larger than Integer.MAX_VALUE
would require something with larger ranges, but that's what the answer is already trying to do.
Also, using less int
s in the representation saves on memory usage.
The code
int decLen = decimal.length();
int bigLen = (decLen-1) / BASE_DECIMAL_DIGITS + 1;
attempts to determine how many int
s are needed in the internal representation to store the incoming number as a String
representation. It's 9 decimal digits per int
. I would have used Math.ceil( (double) decLen / BASE_DECIMAL_POINTS)
.