July LeetCoding Challenge - 1

이선태·2020년 7월 1일
0

Leetcode challenge

목록 보기
1/8
post-thumbnail

Day 1

Arranging Coins

문제

You have a total of n coins that you want to form in a staircase shape, where every k-th row must have exactly k coins.

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

n is a non-negative integer and fits within the range of a 32-bit signed integer.

답(Java)

class Solution {
    public int arrangeCoins(int n) {
        int i = 1;
        while (n >= 0) {
            n -= i;
            i++;
        }
        return i - 2;       
    }
}

주어진 n개의 동전을 가지고 계단을 쌓을 때, 온전한 계단이 몇 칸인지 계산하는 알고리즘이다. n이 32-bit 정수이므로 계단을 한 칸씩 쌓는다고 생각하고 쌓은 만큼을 n에서 빼주었다. While 조건에 '='을 포함하여 n이 0일 때도 올바른 값을 계산하도록 구현했다.

profile
퀀트 트레이딩, 통계에 관심이 많아요

0개의 댓글