Search code examples
javastringsum

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

Solution

  • 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.