This is my function which should add and return the sum of the digits in a string.
public static int Sum(int a) {
String row = String.valueOf(a);
int counter = 0;
int sum = 0;
while (counter<row.length()){
int b = row.charAt(counter);
sum = sum + b;
counter++;
}
return sum;
}
I'm not sure why this does not add all the digits of the integer. Output is giving me completely wonky answers. Help would be appreciated, cheers.
Input: 8576 Output: 218 Expected output: 8+5+7+6 = 26
Fixed:
public static int Sum(int a) {
String row = String.valueOf(a);
int counter = 0;
int sum = 0;
while (counter<row.length()){
String b = String.valueOf(row.charAt(counter));
int c = Integer.parseInt(b);
sum = sum + c;
counter++;
}
return sum;
}