clueless coding // TODO: be smarter

LeetCode 441. Arranging Coins: Java Solution



Problem Statement


You have a grand total of n coins that you want to form into a staircase. Every k-th row must have exactly k coins to be “full”.

Given n total coins, find the total number of full staircase rows that can be formed.

You can assume that n is a non-negative integer and also fits within the range of a 32-bit signed integer.

Function Signature (Java):
  int arrangeCoins(int n)

Inputs:
  n = 5

Outputs:
  2

We can create rows like this:
¤
¤ ¤
¤ ¤
There are 2 full rows.

Inputs:
  n = 8

Outputs:
  3

We can create rows like this:
¤
¤ ¤
¤ ¤ ¤
¤ ¤
There are 3 full rows.



TL;DR Code Solution


public int arrangeCoins(int n) {

    int start = 0;
    int end = n;
    int mid = 0;

    while (start <= end) {
        mid = (start + end) >>> 1;
        if ((0.5 * mid * mid + 0.5 * mid ) <= n) {
            start = mid + 1;
        } else {
            end = mid - 1;
        }
    }

    return start - 1;

}