digitSum function

int digitSum(
  1. int n
)

Returns the sum of the decimal digits of n.

The sign of n is ignored; negatives use their absolute value.

Example:

digitSum(123); // 6
digitSum(-49); // 13

Implementation

int digitSum(int n) {
  int remaining = n.abs();
  int s = 0;
  while (remaining > 0) {
    s += remaining % 10;
    remaining ~/= 10;
  }
  return s;
}