I’m trying to implement some functionality of BigIntegers as a personal programming exercise.
Like many implementations I use an int[] as an unsigned integer.
I want to implement basic functionality like addition, subtraction, multiplication, division, but I’m hitting the problem that I need to get a “human readable” toString out of my data structure for debug purposes, so that I can better inspect and understand what I’m doing.
I feel like I’m stuck. I’m not confident that my algorithms are right, but I have no way to check it.
I have looked at some implementations like Apache Harmony or OpenJDK, but the algorithms they use to create the String look more complex than the actual implementation of plus, minus, … and so on.
Of course I could just use one of those complicated ones, but I would at least want to be able to understand the implementation of it, if I already fail at implementing it myself.
Can someone suggest a simple implementation which converts an int[] to a String?
Example: new int[]{Integer.MAX_VALUE, 1} should be treated as one large, unsigned number and print: 8589934590 (So basically 2³³).
I’d use this approach:
int[]; call itiArr. The rest of this algorithm will operate oniArr.char[]— call its— that is big enough. Since anintcan have up to ten digits, you can uses = new char[iArr.length * 10].int i = s.length - 1. Go throughiArr, dividing by ten, and store the remainder plus'0'ins[i]. Then decrementi. Repeat this process untiliArris zero. (The logic for dividing by ten is roughly: divide each element by ten, noting the remainder. Add that remainder, timesInteger.MAX_INT + 1, to the next element, before dividing that element by ten. Needless to say, you’ll need to do your math usinglong.)new String(s, i, s.length - i).For efficiency’s sake:
1000000or whatnot, to get a bunch of digits at once (obviously this makes thechar-handling trickier, though).iArr, you can keep track of where the first non-zero element is, and ignore any elements before that.but neither of those is actually necessary.
Edited to add actual code. This program:
prints this:
(But you’ll have to examine the
mainmethod, with its comments, to confirm that I’ve correctly understood how you intend to store these integers.)