Reputation: 11
class Solution
{
public:
bool isPowerOfThree (int n)
{
double temp = log10 (n) / log10 (3);
return !(temp - (int) temp);
}
};
in the leetcode problem 326:Power of Three Given an integer, write a function to determine if it is a power of three.
I don't understand how it returns the boolean result.
I expect someone can tell me how to understand this following code: return ! (temp - (int) temp);
Upvotes: 1
Views: 88
Reputation: 206717
The solution relies on temp
being a whole number when n
is some power of 3
and temp
being a number with some fractional value when n
is not a power of 3
.
Let's say n
is 9
.
Then, temp
will be 2.0
.
Then, (temp-(int)temp)
will be 0
and !(temp-(int)temp)
will be true
.
Let's say n
is 10
.
Then, temp
will be 2.0959
.
Then, (temp-(int)temp)
will be 0.0959
and !(temp-(int)temp)
will be false
.
Unfortunately, floating point computations are not that precise. It will be better to use:
double temp = log10 (n) / log10 (3);
double diff = (temp - (int) temp);`
return (std::abs(diff) < tolerance);
where tolerance
can be a small number, such as 1.0E-6
.
My experiment with cygwin/g++ on my computer and at ideone.com suggests that the tolerance can be 1.0e-6
for a large set of numbers but it needs to be almost 1.0e-11
or smaller for INT_MAX. See https://ideone.com/BgnQxV.
Upvotes: 1
Reputation: 7374
temp
is a double
, and (int)temp
truncates it to an int
. Let's say temp is 1.5
, temp - (int)temp
is 0.5
. since the return type is bool
the function will cast the resulting 0.5
to a bool
!(0.5)
which should be false
.
Words from @Nautatava "everything except !(0)
, !(false)
and !(null)
gives false. Thus !(anything other than 0)
is false
."
Upvotes: 1
Reputation: 63481
This code is simply using integer truncation to test whether the number temp
is a whole number. If it is, then temp - (int)temp
will be zero. Since that would then mean the number is a power of three, then the unary "not" operator !
will return true. And of course !
used on any non-zero (true) value will be false.
Upvotes: 0