Java > Recursion-1 > sumDigits (CodingBat Solution)

Problem:

Given a non-negative int n, return the sum of its digits recursively (no loops). Note that mod (%) by 10 yields the rightmost digit (126 % 10 is 6), while divide (/) by 10 removes the rightmost digit (126 / 10 is 12).

sumDigits(126) → 9
sumDigits(49) → 13
sumDigits(12) → 3


Solution:

public int sumDigits(int n) {
  if (n < 10) return n;
  return (n % 10) + sumDigits(n/10);
}


6 comments :

  1. public int sumDigits(int n) {
    if (n <= 0) return n;
    return (n % 10) + sumDigits(n/10);
    }

    ReplyDelete
  2. public int sumDigits(int n) {
    if(n == 0) {
    return 0;
    }
    return n % 10 + sumDigits(n / 10);
    }

    ReplyDelete
  3. public int sumDigits(int n) {
    if (n < 10) return n;
    return (n % 10) + sumDigits(n/10);
    }

    ReplyDelete
  4. //write a recursive function that calculate the sum of the digits
    public int sumDigits(int n) {
    if(n<0)throw new IllegalArgumentException("enter a positive number");
    if(n==0)return 0;
    int rightmost = n%10, leftmost = n/10;
    return rightmost +sumDigits(leftmost);
    }

    ReplyDelete

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact