Find Recursive Sum of Integer

Modulo or Remainder Operator % in java divides the 2 numbers and returns the arithmetical remainder.

3%2 is 1 and 10%5 is 0

package org.wesome.dsalgo;

public class RecursiveSum {
    static int sum = 0;

    public static int recursiveSum(int no) {
        while (no % 10 > 0) {
            sum += no % 10;
            return recursiveSum(no / 10);
        }
        return sum;
    }
}
package org.wesome.dsalgo;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

import static org.wesome.dsalgo.RecursiveSum.recursiveSum;

public class RecursiveSumTest {
    @Test
    void recursiveSumTest1() {
        int integer = 12345;
        int finalSum = recursiveSum(integer);
        Assertions.assertEquals(15, finalSum);
    }
}
plugins {
    id 'java'
}

group = 'org.wesome'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = JavaVersion.VERSION_1_8

repositories {
    mavenCentral()
}
dependencies {
    testImplementation('org.junit.jupiter:junit-jupiter:5.6.2')
}

test {
    useJUnitPlatform()
}

 

follow us on