0

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);
    }
}

}
Alan
  • 361
  • 3
  • 22

2 Answers2

2

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)

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
0

This question addresses your problem: How to handle very large numbers in Java without using java.math.BigInteger

you could also use BigInteger

Community
  • 1
  • 1
duebstep
  • 187
  • 1
  • 3
  • 13