본문 바로가기

Algorithm/Implementation

(C++) - LeetCode (easy) 441. Arranging Coins

반응형

https://leetcode.com/problems/arranging-coins/description/

 

Arranging Coins - LeetCode

Can you solve this real interview question? 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. Give

leetcode.com

구현 문제였습니다.

📕 풀이방법

📔 입력 및 초기화

정답 ans를 선언해줍니다. 상기 이미지의 한 행을 나타냅니다.

📔 풀이과정

n은 전체 coin, ans는 한 행을 나타내므로 n에서 ans를 빼고 1씩 증가시켜 주는 방식으로 loop를 수행합니다.n에서 ans만큼 즉, 한 행씩 빼면서 남은 동전이 채워야 될 현재 행 ans보다 작거나 같으면 1을 증가하지 않고 break 해줍니다.

📔 정답 출력 | 반환

ans를 반환합니다.


📕 Code

📔 C++

class Solution {
public:
    int arrangeCoins(int n) {
        int ans = 1;
        while(1) {
            n -= ans;
            if(n <= ans) break;
            ans++;
        }
        return ans;
    }
};

*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.