All puzzles
Per page
B
Digits ยท Sum

Add up the digits

Return the sum of the digits of the positive integer n.

digitSum(4071) returns 12.

9 strips: B1 to B9

n /= 10;
B1
sum += n % 10;
B2
}
B3
}
B4
sum += n / 10;
B5
while (n > 0) {
B6
int sum = 0;
B7
return sum;
B8
public static int digitSum(int n) {
B9

Answer key: B. Add up the digits

Order: B9, B7, B6, B2, B1, B3, B8, B4. Extra: B5

public static int digitSum(int n) {
	int sum = 0;
	while (n > 0) {
		sum += n % 10;
		n /= 10;
	}
	return sum;
}

Extra strip: sum += n / 10;. n / 10 is the number with its last digit cut off. The last digit is n % 10.