I actually think I see what your for loop is supposed to do, it's a little pow function. But as some others have pointed out, d
starts out as 0 so it always ends up 0.
Just changing d
to 1 will stop your infinite loop:
for (d = 1; d < n; d *= 10);
But the answer is still wrong since it looks like you're trying to sum the digits. (e.g. 1 + 2 + 3 = 6
, but instead the answer returned is 3.53
)
Since you are dealing with the individual digits, using float is bad here because you don't want fractional values. You want the digits to round. So you need to change your temp variables to int.
There's one last thing which is the last digit is skipped. At this point I get 3
as the answer. After changing while(n > 10)
to while(n > 0)
, the right answer is returned.
So the code would be this:
public static int sumDigits(int n) {
int retVar = 0;
while (n > 0) {
int d;
for (d = 1; d < n; d *= 10);
d /= 10;
retVar += n / d;
n %= d;
}
return retVar;
}
As a tip, there's a simpler way to solve this same problem which is to start with the smallest digit instead of the largest:
while(n > 0) {
retVar += n % 10;
n /= 10;
}
Final Note
If I'm right about the for loop, the important thing to take home is that if you write stuff like this almost nobody will think it's intentional. Syntax like this might actually work correctly but it's obscure and more like a novelty.
The loop can be replaced like this which is much more clear and just as compact:
int d = 0;
while(d < n) {
d *= 10;
}
Or if you really want:
int d = 0;
while(d < n) d *= 10; // not recommended but clearly has a body