简体   繁体   中英

Recursively add digits in Java BigInteger

Below is what I have so far but compiler states method needs to return BigInteger.

private static BigInteger recSum(BigInteger val, BigInteger moddiv, BigInteger result){
    if(moddiv.compareTo(val) == 1){
        return result;
    }else{
        val = val.mod(moddiv);
        moddiv = moddiv.multiply(BigInteger.valueOf(10));
        result = result.add(recSum(val, moddiv, result));
    }
}

I'm basically looking to pass an argument to this method through val and find the sum of all the digits of that number. Just for practice it seemed recursion could work here, opposed to say converting it to a string and parsing out each character to a value and adding.

Basically if starting with 1524, 1+5+2+4

Writing it out I figured it looked like this:

(1524%10)+([1524-(1524%10)]%100)+([1524-([1524-(1524%10)]%100)]%1000)...

Writing it out like that I see my current code will stop short, but also there is something missing regardless.

Oh and I guess if my code would work it would probably do something like

1000+500+20+4

I could easily rearrange things and divide by the moddiv before incrementing it to the next power. The thing is at some point it isn't returning a BigInteger.

Any advice?

Your function has no return statement is the else clause. You should return result there too.

Or better yet, rearrange your code to have a single return statement :

private static BigInteger recSum (BigInteger val, BigInteger moddiv, BigInteger result)
{
    if (moddiv.compareTo(val) != 1){
        val = val.mod(moddiv);
        moddiv = moddiv.multiply(BigInteger.valueOf(10));
        result = result.add(recSum(val, moddiv, result));
    }

    return result;
}

You forgot the return statement:

private static BigInteger recSum(BigInteger val, BigInteger moddiv, BigInteger result){
    if(moddiv.compareTo(val) == 1){
        return result;
    }else{
        val = val.mod(moddiv);
        moddiv = moddiv.multiply(BigInteger.valueOf(10));
        result = result.add(recSum(val, moddiv, result));
        return result; // <-- need return statement here
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM