Java 3-Liner


  • 7
    public static boolean judgeSquareSum(int c) {
      for (int i=0;i<=Math.sqrt(c);i++) 
        if (Math.floor(Math.sqrt(c-i*i)) == Math.sqrt(c-i*i)) return true;
      return false;
    }  
    

  • 0
    T

    Very awesome!


  • 0

    Thanks for sharing!,
    BTW, Does it need to add?

    if(c == 0) return true;
    

  • 0
    L

    In the 3rd line, you're doing floating point comparison which might not be sufficient due to rounding errors. Is your idea based on some fact that the difference between Math.floor(Math.sqrt(c-i*i)) and Math.sqrt(c-i*i) won't be greater than a certain number? Can you provide explanation? IMO comparing integers is safer and more intuitive.

    for (int i=0;i<=Math.sqrt(c);i++) {
       int j = (int)Math.sqrt(c-i*i);
       if (j*j == c-i*i) return true;
    }
    return false;
    

  • 0
    D

    Feels like magic
    Can you please explain the logic ?


Log in to reply
 

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