Find the sum of digits of a number in Java

We can very easily get the sum of digits of an integer number in Java. We can do in multiple ways.

Approach 1
We can simply convert the number to string and then loop through the string upto the length get the char from string. Once we get the char from string then again convert the char to numeric and sum it. Following is the functional code:

// one class needs to have a main() method
public class HelloWorld
{
  // arguments are passed using the text field below this editor
  public static void main(String[] args)
  {
    Integer number = 101010;
    int result = 0;
    
    String strNumber = Integer.toString(number);
    for(int i = 0; i < strNumber.length() ; i++){
      result += Character.getNumericValue(strNumber.charAt(i));
    }
    System.out.println(result);
  }
}


Approach 2
We can simply use divide and modulus tricks to get the digit and sum it up. Following is the functional code:


// one class needs to have a main() method
public class HelloWorld
{
  // arguments are passed using the text field below this editor
  public static void main(String[] args)
  {
    Integer number = 101010;
    int res =0;
    
    while (number > 0) {
       res += number % 10;
       number = number / 10;
    }
    System.out.println(res);
  }
}

Comments