 <p>Observe that:</p> <ul> <li>For the number XY you have 11X + 2Y.</li> <li>For the number XYZ you have 111X + 22Y + 3Z.</li> <li>For WXYZ, you have 1111W + 222X + 33Y + 4Z.</li> </ul> <p>Here's my C# implementation, though it should be trivial to port to Java:</p> <pre><code>static long SumSubtring(String s) { long sum = 0, mult = 1; for (int i = s.Length; i &gt; 0; i--, mult = mult * 10 + 1) sum += (s[i - 1] - '0') * mult * i; return sum; } </code></pre> <p>Note that it is effectively O(n).</p>