Kaif
Kaif

Reputation: 131

Sum of any digits of numbers

I think this one is easy ques,but I want to know how to sum any no of digits in java.

There is specific range of datatype if we add any no to its MAX_VALUE, it prints the -ve no.

e.g 12344587387873878 + 374892 = ?

Any logic.

Upvotes: 0

Views: 143

Answers (2)

Rudi Kershaw
Rudi Kershaw

Reputation: 12972

If you want to store any number (technically your example could be a long) you will want to use BigDecimal. BigInteger can also be used if you know that your sum will be a whole number.

BigDecimal Example;

BigDecimal bigD1 = new BigDecimal(1234458738787.387*1000);
BigDecimal bigD2 = new BigDecimal(374892.5);
System.out.println(bigD1.add(bigD2));

Output: 1234458739162279.5.

As 12344587387873878 is too big to store as an integer you can't just type it in as a literal (all non-floating point literals are implicitly ints) to go into your BigDecimal constructor. So I divided it by 1000 myself, and then *1000 in the constructor. Alternatively you could use scientific notation.

OR, you can pass BigDecimal a string.

BigDecimal bigD1 = new BigDecimal("1234458738787387");

As a warning, BigDecimal does have it's issues with very high accuracy numbers. It can not accurately represent Pi, or even 1/3rd for example.

Upvotes: 1

peter.petrov
peter.petrov

Reputation: 39457

You can use BigInteger for this.

Look at the BigInteger class.

Additionally you can implement that yourself.

See here:

How would i add very large Numbers represented as Strings i.e 50 digit numbers

Upvotes: 2

Related Questions