C++ solution compare double and its floor


  • 1
    S

    C++ solution compare double and its floor(or ground) number. float is ok in this problem.

    class Solution {
    public:
        bool isPowerOfThree(int n) {
            if(n <= 0) return false;
            double x = log10(n)/log10(3);
            return x == floor(x);
        }
    };

  • 0
    F

    Hi,
    Could you explain why do you choose floor? Don't quite catch this point.
    Thanks


  • 0
    S

    floor of 2.3 is 2.0 and floor of -2.3 is -3.0, Therefore, no matter the number x is positive or not, I just want to determine that it's a integer(0 after point). If x is an integer, so x == floor(x) should return true.


  • 0
    W

    this method is not always reliable under finite precision. I tried change log10(n)/log10(3) in your code to log(n)/log(3) and now it can't pass test cases.


  • 1

    Tried that in Java, didn't quite work (FP precision). So I had to change it a little bit:

    1. Don't use floor(), use round() (if your language / library has that, otherwise do it yourself).
    2. Don't compare for equality. Instead, find the smallest tolerance that works and use it. By experimenting, I figured that 1E-11 works quite nice for all possible powers of three within 32-bit range.

  • 0
    S

    I am not sure if there is precision problem if translate it to Java, so round() might be better, at least make more sense. Thanks.


  • 0

    Java or not, comparing FP using equality is usually a very bad idea. I know one case when a number was not equal to itself because at some point it was internally converted by the compiler between 64 and 80 bit representation and comparison used all 80 bits.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.