A question about Java Math.sqrt().


  • 0
    I

    Hi guys:

    I know that simple code like:

    int sqrt = (int) Math.sqrt(num);
        
    return sqrt * sqrt == num;
    

    will work but I do have a question here. I think that cast the result of sqrt() to int will get us a floored value, e.g. (int) Math.sqrt(24) will return 4. Is it possible that using sqrt on a perfect square number will result in a x.99999999 double number and finally lead us to the wrong answer?

    Thanks


  • 0

    maybe, you can use (int) Math.round(Math.sqrt(num)) to avoid that.


  • 0

    maybe, you can use (int) Math.round(Math.sqrt(num)) to avoid that.


Log in to reply
 

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