1

How to handle 1000 digit number? Anyone can explain it?

My code;

 Long sum = 1L;
 ...

 if (String.valueOf(sum).length() == 1000) {
    ...
 }

But not working, anyone can explain it?

Semih Eker
  • 2,389
  • 1
  • 20
  • 29
  • 2
    try a Google search for `BigDecimal` – Matt Jan 23 '14 at 15:15
  • 2
    Your question is not clear, and you should do some research first. – DarthVader Jan 23 '14 at 15:17
  • 1
    @SemihEker After ... the maximum length of sum can be Long.MIN_VALUE (that is -9223372036854775808), which is a far cry from 1000 digits. Any operation that would overflow the capacity of the Long data type will simply end up with the Long containing the least significant 64 bits of the result. This is commonly called "Integer overflow". All primitive (fixed length types) exhibit some kind of overflow, to precisely represent numbers with more digits you will need to use a variable length type. The JDK offers BigInteger and BigDecimal for that purpose. – Durandal Jan 23 '14 at 15:21

2 Answers2

5

Use the class BigInteger, it can handle arbitrary long numbers (that is, as big as computer memory allows).

Link: http://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html

Jakub Zaverka
  • 8,816
  • 3
  • 32
  • 48
1

Use a BigInteger instead. See the documentation here.

mrjink
  • 1,131
  • 1
  • 17
  • 28