I am assigned to a task of creating a function int logBase10Estimate(int n) that returns the log of a number base 10. The answer is integer part only.(w/o using the Math class)
Is this okay?
static int logBase10Estimate(int n){
int count = 0;
for(int x = 10; ;x*=10){
if(x < n){
count+=1;
System.out.println(x);
}
else if(x == n){
count+=1;
break;
}
else{
break;
}
}
return count;
}
2 Answers 2
The printing should not be there :)
You don't need another variable x
. You can modify the local copy n
, because you won't need its original value for the entire algorithm and because it is passed by value, you won't change the value for the caller.
Also check for valid input.
static int logBase10Estimate(int n)
{
if (n <= 0) {
throw new IllegalArgumentException('Log of non-positive number is undefined');
}
int count = 0;
for (; n>=10; n/=10) {
++count;
}
return count;
}
-
\$\begingroup\$ Sorry i forgot to remove the print function...Can i ask of what's the difference of putting an increment before and after a variable in a loop? \$\endgroup\$zvz– zvz2020年04月01日 14:35:50 +00:00Commented Apr 1, 2020 at 14:35
-
\$\begingroup\$ @ZiegfredZorrilla Postfix vs prefix \$\endgroup\$2020年04月01日 14:45:04 +00:00Commented Apr 1, 2020 at 14:45
You have the possibility of an infinite loop.
Consider: logBase10Estimate(2147483647)
. Should be about 9. We need a value of \10ドル^i\$ which is greater than 1000000000. So, what values does x
take on?
10
100
1000
10000
100000
1000000
10000000
100000000
1000000000
1410065408
1215752192
-727379968
1316134912
276447232
-1530494976
1874919424
1569325056
-1486618624
: : :
Any value of num
greater than 1000000000
is going to give incorrect results. And some values, like 2147483647
will never give an answer, because no int
value is greater than it, and x
will never be odd, so it will never be equal to it either.
Not only is slepic's solution cleaner, it is correct and it terminates for all values.
Explore related questions
See similar questions with these tags.
round(sqrt(10))
. \$\endgroup\$int count = 0; for(; n; n/=10) { ctr++; } return count;
? \$\endgroup\$round(sqrt(10))=3
btw ;) \$\endgroup\$3
does not tell why/how it was chosen.) \$\endgroup\$