441. Arranging Coins

Doosan published on
1 min, 108 words

Categories: Leet code

Problem

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.

Example 1.

1

Input: n = 5
Output: 2
Explanation: Because the 3rd row is incomplete, we return 2.

Example 2.

2

Input: n = 8
Output: 3
Explanation: Because the 4rd row is incomplete, we return 3.

Solution

impl Solution{
    pub fn arrange_coins(n: i32) -> i32{
        let mut l:i64 = 0;
        let mut h:i64 = n as i64;

        while l<=h{
            let m:i64 = l+(h-l)/2;
            let mut p:i64 = m*(m+1)/2;

            // p 를 i32로 변환하면 이상하게도 엄청 큰 수가 나옴 그래서 n을 i64로
            if p == n as i64{
                return m as i32;
            }
            if p > n as i64{
                h = m-1;
            } else {
                l = m+1;
            }
        }
        (l-1) as i32
    }
}