Emolk - 7 months ago 43

Java Question

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;

}

Answer

`int b = Row.charAt(i);`

is the problem. the integer gets the ascii value of the character.
working code is :

```
public static int Sum(int a) {
int sum = 0;
int rest = 1;
while(rest!=0){
rest = a % 10;
a = a / 10;
sum = sum + rest;
}
return sum;
}
```

rest is always the last digit and since int is always a non-decimal dumber and rounds automatically you can can use `a = a / 10;`

to "delete" the last digit

Source (Stackoverflow)