Sum of all the digits till it becomes single digit in java with o(1) complexity?
<p>I found the answer for this from Henry </p>

<pre><code>int sum = n % 9;
if (sum == 0) sum = 9;
</code></pre>

<p>here</p>

<p><a href="https://stackoverflow.com/questions/21940981/java-program-that-sums-up-the-digits-of-a-number-until-it-is-a-single-number-eg">java program that sums up the digits of a number until it is a single number Eg: 2748303 = 2+7+4+8+3+0+3 = 27 = 2+7 = 9</a></p>

<p>Can any one please explain how adding digits and remainder are related?</p>

<p>My logic also would have been as below which is also mentioned in above link</p>

<pre><code>int sum = 0;
    while (n &gt; 9 ) {
                 sum=0;
        while (n &gt; 0) {
            int rem;
            rem = n % 10;
            sum = sum + rem;
            n = n / 10;
        }
        n = sum;
    }
</code></pre>

<p>But 2 line answer is awesome.</p>