简体   繁体   中英

Java Integer add leading zeros?

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.

Have you considered using Java's BigInteger class?

eg

BigInteger quiteBig = new BigInteger("534989378445891459824893358947");

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM