[C][JAVA] Elegant One Line of Code, Clear Explanation Provided


  • 3
    K

    C solution:

    int arrangeCoins(int n) {
        return (int) floor((-1 + sqrt(1+8L*n))/2.0);
    }
    

    Java solution:

    public int arrangeCoins(int n) {
            return (int) Math.floor((-1 + Math.sqrt(1+8L*n))/2.0);
    }
    

    Explanation:

    The solution starts with the following mathematical expression:

    1+ 2 + 3 + ... + x = n
    => (x (x + 1))/2 = n  
    

    n is the input of the problem, we need to solve for x the following quadratic equation:

    x (x + 1)= 2n 
    => x^2 + x - 2n = 0
    

    Resulting with the final formula:

    using: x= (-b + sqrt[ b^2 - 4 a* c])/2a  { a=1, b=1, c=-2 }
    
    x= floor((-1 + sqrt(1+8*n))/2);
    

  • 0
    G

    I think we can skip the floor function because the int cast will do


Log in to reply
 

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