Search code examples
javadigits

Java: How can I Sum Digits of a huge number n that is 10^19 < n <=10^20?


Hello I'm having problems operating a large number, made a program that it's meant to sum digits from a number that can go up to 10^20. But it breaks at around 10^19 using doubles.

What type am I supposed to use? I've tried Double and Long, yet I'm getting wrong answer for huge numbers.

import java.util.Scanner;

public class SumDigit{

public static void main(String [] args){
    Scanner sc = new Scanner(System.in);
    int cases = sc.nextInt();

    for(int i=0; i<cases; i++){
        double number = sc.nextDouble();
        System.out.println(sum(number,0));
    }
}

public static int sum(double number, int total){
    double digit;

    if(number < 10){
        total += number;
        int totalT = (int) total;
        return totalT;
    }

    else{
        digit=(number%10);
        total += digit;
        return sum(number/10, total);
    }
}

}

Solution

  • It is probably easiest to do it with a String containing your number:

    int sumOfDigits(String str) {
      int sum = 0;
      for (char c : str.toCharArray()) {
        sum += Character.digit(c, 10);
      }
      return sum;
    }
    

    (I guess you'd also want some validation that your string only contains digits)