title: Number of digits in an integral number (large size)
body: <p>I have a collection of <a href="https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html" rel="nofollow noreferrer"><code>BigInteger</code></a>s and am trying to get the number of digits in each integral number. For the sake of brevity, lets say that we are only dealing with <em>positive</em> numbers. We are looking at numbers with over 1000 digits. </p>
  
  <p>The following are the ways I have thought of.</p>
  
  <ol>
  <li><p>length of a string representation (will require a bunch of memory) </p></li>
  <li><p>modulo 10 approach (slow)  </p></li>
  <li><p>an asanine idea (included for sake of thoroughness, since scalability of this approach is not great)</p>
  
  <pre><code>if (i &gt;= 100000000) {
      i /= 100000000;
      n += 8;
  }
  if (i &gt;= 10000) {
      i /= 10000;
      n += 4;
  }
  if (i &gt;= 100) {
      i /= 100;
      n += 2;
  }
  if (i &gt;= 10) {
      i /= 10;
      n += 1;
  }
  </code></pre></li>
  <li><p>logarithms (which I find rather friendly) (credits go to [<a href="https://stackoverflow.com/a/7982137/1692706">this answer</a>])</p>
  
  <pre><code>int blex = val.bitLength() - 1022; // any value in 60..1023 is ok
  if (blex &gt; 0)
      val = val.shiftRight(blex);
  double res = Math.log10(val.doubleValue());
  return blex &gt; 0 ? res + blex * LOG2 : res;
  </code></pre></li>
  <li><p>This is an idea I have but want to test the validity of before coding; say I have some number <code>x</code>. Try to divide by powers of 10 using concepts of (traditional or one-sided) binary search, and stop when <code>0 &lt; quotient &lt; 10</code>. That <code>power + 1</code> should be the number of digits. This would be a logarithmic solution (?).</p></li>
  </ol>
  
  <p>StackOverflow did not really seem to have something solid to calculate the number of digits in <strong>any number</strong>. This <a href="https://stackoverflow.com/a/18860385/1692706">accepted answer</a> suggests a division-heavy approach that can result in a bunch of new objects being created. I was wondering if there can be a slicker solution. So, I thought this post would lead to a fruitful discussion and collaboration of ideas. Please suggest which method would work best for really large numbers.</p>