@@ -0,0 +1,1668 @@
+import org.junit.After;%0Aimport org.junit.Assert;%0Aimport org.junit.Before;%0Aimport org.junit.Test;%0A%0A/**%0A * Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.%0A * %3Cp%3E%0A * For example:%0A * %3Cp%3E%0A * Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.%0A * %3Cp%3E%0A * Follow up:%0A * Could you do it without any loop/recursion in O(1) runtime?%0A * %3Cp%3E%0A * Hint:%0A * %3Cp%3E%0A * 1. A naive implementation of the above process is trivial. Could you come up with other methods?%0A * 2. What are all the possible results?%0A * 3. How do they occur, periodically or randomly?%0A * 4. You may find this Wikipedia article(https://en.wikipedia.org/wiki/Digital_root) useful.%0A * %3Cp%3E%0A * Tags: Math%0A * Similar Problems: (E) Happy Number%0A */%0Apublic class AddDigits %7B%0A%0A    private AddDigits ad;%0A%0A    /**%0A     * Possible results range from 0 to 9.%0A     * Only when num is 0, the result is 0; Otherwise, the result is within 1 to 9.%0A     * It happens periodically as the num increases one by one.%0A     */%0A    public int addDigits(int num) %7B%0A        if (num == 0) return 0;%0A        return num %25 9 == 0 ? 9 : num %25 9;%0A    %7D%0A%0A    @Before%0A    public void setUp() %7B%0A        ad = new AddDigits();%0A    %7D%0A%0A    @Test%0A    public void testEdgeCases() %7B%0A        Assert.assertEquals(0, ad.addDigits(0));%0A    %7D%0A%0A    @Test%0A    public void testExamples() %7B%0A        for (int i = 0; i %3C 10; i++) %7B%0A            Assert.assertEquals(i, ad.addDigits(i));%0A        %7D%0A        Assert.assertEquals(2, ad.addDigits(38));%0A        Assert.assertEquals(1, ad.addDigits(100));%0A    %7D%0A%0A    @After%0A    public void tearDown() %7B%0A        ad = null;%0A    %7D%0A%0A%7D%0A

add Add Digits