2

I need to add leading zeros to an array for mathematical use. Specifically, I am making something to add two large numbers. The numbers are stored as an int array, where each element of the array is 5 digits. One example is 53498 93784 45891 45982 48933 58947 I need to add another to this, say, 23584 42389 32479 34289 39281 48237 To add them I would take the last 5 digits of both and add them 58947+48237 This gives 107184. Then I set the carry value to 1 and subtract 100,000.

This is the problem: It sets the int to 7184, then the sum says ...882157184 instead of 8821507184, making a (very) incorrect sum. So how do I get my Sum int array to say 88215 07184? If this is not possible, please list another way of getting the same result, maybe a string instead of a int array? If at all possible, please try to find a way to have a leading 0 with an int value.

JTTCOTE
  • 131
  • 1
  • 2
  • 6
  • Are you looking for a way of *printing* a number with leading zeros? – Ilya Kogan Jan 02 '12 at 00:31
  • 7
    Numeric values *never have leading zeros*. However, a *string representation* of a number can have leading zeros (often for human consumption). The *numeric value* is still the same, however. If you want to treat a number as a string, then do so. But know that any leading zeros *have no meaning* to the value of the number -- or `int` -- itself. –  Jan 02 '12 at 00:35
  • Unless this is home work, use BigInteger. If its homework (you should add the `[homework]` tag) you shouldn't need to worry about leading zeros because all `int` values are 32-bits long regardless of their values i.e. they always have the same number of 0 or 1s. – Peter Lawrey Jan 02 '12 at 11:21
  • @JTTCOTE: If an answer helped you, please don't forget to accept/upvote it. – Mitch Wheat Jan 11 '12 at 09:18

3 Answers3

14

Have you considered using Java's BigInteger class?

e.g.

BigInteger quiteBig = new BigInteger("534989378445891459824893358947");
Community
  • 1
  • 1
Mitch Wheat
  • 295,962
  • 43
  • 465
  • 541
4

There's no leading zeros in the value (unless of course you're talking about octal literals). Internally, int is 32 bits, and that's it.

What you may need is formatting. To address the output, you can try String.format("%05d", x);, For the detais, see javadoc

alf
  • 8,377
  • 24
  • 45
0

You could start with something like this:

class FiveDigitInteger {
  private static final DecimalFormat format = new DecimalFormat("00000");
  final int i;

  public FiveDigitInteger ( int i ) {
    this.i = i;
  }

  public int getInteger () {
    return i;
  }

  public String toString () {
    return format.format(i);
  }
}

and add various math methods such as:

  public FiveDigitInteger add ( int j ) {
    return new FiveDigitInteger ( i + j );
  }

etc.

OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213