Ask Question
30 May, 02:52

Write a recursive function called sumDigits with the following signature: public static long sumDigits (long n) that computes the sum of the digits in a number repeatedly, until the sum is a single digit. For example, if we call sumDigits (123456), the following would result: sumDigits (123456) = > 1+2+3+4+5+6 = > 21 = > 2+1 = > 3 so the final answer would be 3. You must meaningfully use recursion for this lab in order to receive any credit. Hint: For this problem it might be useful to convert back and forth between longs and strings. This can be done using the Long. parseLong method and the Long. toString method.

+3
Answers (1)
  1. 30 May, 05:18
    0
    Here you go:

    public static long sumDigits (long n) {

    if (n < 10) {

    return n; / / our exit criterion

    }

    String str = Long. toString (n);

    long sum = 0;

    for (int i=0; i
    sum + = Character. getNumericValue (str. charAt (i));

    }

    return sumDigits (sum);

    }
Know the Answer?
Not Sure About the Answer?
Find an answer to your question ✅ “Write a recursive function called sumDigits with the following signature: public static long sumDigits (long n) that computes the sum of ...” in 📘 Computers and Technology if you're in doubt about the correctness of the answers or there's no answer, then try to use the smart search and find answers to the similar questions.
Search for Other Answers