Brian
Brian

Reputation: 67

sum of digits of an integer

The following two methods work.

public static int sumInt(int num) {
    int sum;
    for (sum = 0; num != 0; num = num/10) {
        sum += num % 10;
    }
    return sum;
}

and

public static int sumInt(int num) {
    int sum = 0;
    while (num != 0) {
        sum+= num%10;
        num = num/10;
    }
    return sum;
}

But I was wondering about doing something where the program reads the input as a string and then uses charAt() to check each index of the string then subtract '0' from each and add those all together. It probably is not as efficient, but can it be done? Here is what I have so far but it's not quite right:

import java.util.Scanner;

public class SumDigitsString {
    public static void main (String[] args ) {
        Scanner input = new Scanner (System.in);
    
        System.out.print("Enter an integer:  ");
        String number = input.next();
        System.out.println("\nThe sum of the digits of " + number + " is " + sumInt(number));
    }   

    public static String sumInt(String num) {

        int sum = 0;

        while (num.length() - num.charAt() > 0)
        sum += (num.charAt(num.length())) + '0';
        num.charAt()++;
        return sum;
    }
}

Upvotes: 0

Views: 1075

Answers (4)

Reinier Garcia
Reinier Garcia

Reputation: 1680

This can be also solved by using recursion. There is two recursive approaches to this task:

Approach # 1: Keeping the sign

    public static int digitsSum(int number) {
        if (Math.abs(number) > 9) {
            return number % 10 + digitsSum(number / 10);
        }
        return number;
    }

Approach # 2: Using the absolute value (no sign)

    public static int absDigitsSum(int number) {
        if (Math.abs(number) > 9) {
            return Math.abs(number % 10) + absDigitsSum(Math.abs(number) / 10);
        }
        return Math.abs(number);
    }

Testing both ways:

    public static void main(String[] args) {
        int sum1 = digitsSum(-125);
        System.out.println(sum1);
        int sum2 = digitsSum(125);
        System.out.println(sum2);

        System.out.println(" ");

        int sum3 = absDigitsSum(-125);
        System.out.println(sum3);
        int sum4 = absDigitsSum(125);
        System.out.println(sum4);
    }

Result on the terminal

-8
8
 
8
8

Upvotes: 0

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 78945

You can do it as follows:

public static int sumInt(String num) {
      int sum = 0, i = 0;
      while (i < num.length()) {
            char ch = num.charAt(i);
            if (Character.isDigit(ch)) {
                  sum += ch - '0';
                  i++;
            } else {
                  throw new IllegalArgumentException(num + " is not a whole number.");
            }
      }
      return sum;
}

A sample run:

Enter an integer:  1234

The sum of the digits of 1234 is 10

Another sample run:

Enter an integer:  12a34
Exception in thread "main" java.lang.IllegalArgumentException: 12a34 is not a whole number.
    at Main.sumInt(Main.java:20)
    at Main.main(Main.java:9)

The idea is to add the numeric value of each digit to a variable (sum in the code given above) initialized with 0. Note that it's also important to check if the character is a digit and throw some exception if it is not.

The ASCII value of '0' is 48 and therefore to get the numeric value of '0', you need to subtract '0' or 48 from '0'. Similarly, The ASCII value of '1' is 49 and therefore to get the numeric value of '1', you need to subtract '0' or 48 from '1'. In summary, in order to get the numeric value of a digit character, we need to subtract '0' or 48 from it.

Upvotes: 0

Rohan Kumar
Rohan Kumar

Reputation: 5872

Umm, why don't you just use nextInt() instead? I think it's always better to rely on Java libraries(which are always tried and tested by community) rather than rewriting code yourself :-)

Scanner input = new Scanner(System.in);
System.out.println("Enter an integer: ");
int number = input.nextInt();
// Call your old sumInt(int) method 
System.out.println("\nThe sum of the digits of " + number + " is " + sumInt(number));

I think you're not using charAt properly. I don't think num.charAt()++ is even sytaxwise correct. You should do something like this:

public static int sumInt(String num) {
    int sum = 0;
    for (int i = 0; i < num.length(); i++) {
        sum += (num.charAt(i) - '0');
    }
    return sum;
}

Upvotes: 0

Kavfixnel
Kavfixnel

Reputation: 331

What you can do is this:

public static int sumInt(String num) {
  int sum = 0;
  for (int i = 0; i<num.length(); i++)
    sum += num.charAt(i) - '0';
  return sum;
}

If you take the character at index i and subtract '0', you get the value of the character as per the ASCII table and it then gets converted implicitly into an interger when you add it to sum.

Upvotes: 1

Related Questions