Complete-Preparation

🎉 One-stop destination for all your technical interview Preparation 🎉

View the Project on GitHub

441. Arranging Coins 🌟

You have n coins and you want to build a staircase with these coins. The staircase consists of k rows where the ith row has exactly i coins. The last row of the staircase may be incomplete.

Given the integer n, return the number of complete rows of the staircase you will build.

Simulation

Code

class Solution{
public:
    int arrangeCoins(int n){
        long i = 0, sum = 0;
        while (sum <= n){
            i++;
            sum += i;
        }
        return i - 1;
    }
};

Code

class Solution{
public:
    int arrangeCoins(int n){
        long long l = 0, r = n;
        long long mid = 0, total = 0;
        while (l <= r){
            mid = l + (r - l) / 2;
            total = mid * (mid + 1) / 2;
            if (total == n)
                return ((int)mid);
            if (n < total)
                r = mid - 1;
            else
                l = mid + 1;
        }
        return ((int)r);
    }
};

Math solution

Code

class Solution{
public:
    int arrangeCoins(int n){
        return floor(-0.5 + sqrt((double)2 * n + 0.25));
    }
};