How do I write a recursive method to return the sum of digits to an int?
So this is my code.
public int getsum (int n){
int num = 23456;
int total = 0;
while (num != 0) {
total += num % 10;
num /= 10;
}
}
The problem is I cant / know how to change this to a recursive method Im kind of new with recursion and I need help implementing this method to change it so that it is recursive.
+3
source to share
12 replies
Here he is,
//sumDigits function
int sumDigits(int n, int sum) {
// Basic Case to stop the recursion
if (n== 0) {
return sum;
} else {
sum = sum + n % 10; //recursive variable to keep the digits sum
n= n/10;
return sumDigits(n, sum); //returning sum to print it.
}
}
An example of a function in action:
public static void main(String[] args) {
int sum = sumDigits(121212, 0);
System.out.println(sum);
}
+6
source to share
public static int sumOfDigit(int num){
int sum=0;
if (num == 0)
return sum;
sum = num%10 + sumOfDigit(num/10);
return sum;
}
public static void main(String args[]) {
Scanner input=new Scanner(System.in);
System.out.print("Input num : ");
int num=input.nextInt();
int s=sumOfDigit(num);
System.out.println("Sum = "+s);
}
}
+1
source to share
import java.util.Scanner;
public class Adder {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
System.out.println();
int number = input.nextInt();
System.out.println("The sum of the digits is " +adder(number));
}
public static int adder(int num){
int length = String.valueOf(num).length();
int first , last , sum;
if (length==1){
return num;
}
else
{
first = num /10;
last = num % 10;
sum = last + adder(first);
}
return sum;
}
}
0
source to share