简体   繁体   中英

Find the sum of the digits of a number in Java

I'm new to Java and I've come up with a solution for a Euler Problem

public class Problem16{

    public static void main(String[] args){
        System.out.println(DecomposeNumber(PowerDigitSum(1000)));
    }// end main

    public static double PowerDigitSum(double iExposant){
        return Math.pow(2, iExposant);
    }// end PowerDigitSum()

    public static int DecomposeNumber(double iNb){
        int[] intTab = String.valueOf(iNb).chars().map(Character::getNumericValue).toArray();
        int iMax = intTab.length;
        int sum = 0;
            for(int i = 0; i < iMax; i++){
                sum += intTab[i];
            }
            return sum + 1;
    }// end DecomposeNumber()

}// end classe

What I don't understand is my solution works for small numbers such as n^15 but not n^1000 for example, I understand it doesn't work because the number isn't a full set of digits but is there a way to convert let's say 1.071509e+301 into full digits?

If I got your question right, you want to print a big double without scientific notation. you can do that using String.format() .

String stringNumber = String.format("%f", iNb);

While the other answer certainly solves a part of your problem. I don't recommend using the double type for a computation as such of 2 ^ 1000 .

The answer to your problem is to utilise BigInteger . As a hint, I will provide the logic for the PowerDigitSum method and I'll leave the rest of the logic as an exercise as you're trying to learn from it.

The function PowerDigitSum now becomes:

public static BigInteger powerDigitSum(int exponent){
      return BigInteger.TWO.pow(exponent); // 2 ^ exponent
}

Note, if you're going to proceed with this approach (which I hope you do) then after the call to map in the stream pipeline inside the DecomposeNumber method, you can simply call .sum() and return the result instead of toArray() , this means you don't need to perform the subsequent loop to sum the digits.

Here is an implementation using BigInteger and no string conversions. As it turns out, modulo of large double values is no better than the string approach.

Note that this is actually the basis of a string conversion, without the overhead that isn't needed in this case.

int sumDigits(BigInteger number) {
    int sum = 0;

    while (number.compareTo(BigInteger.ZERO) > 0) {
        sum += number.mod(BigInteger.TEN).intValue();
        number = number.divide(BigInteger.TEN);
    }

    return sum;
}

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