본문 바로가기

Algorithm/Implementation

(C++) - LeetCode (easy) 1556. Thousand Separator

반응형

https://leetcode.com/problems/thousand-separator/description/

구현문제였습니다.

📕 풀이방법

📔 입력 및 초기화

n의 문자열 형태 str과 정답변수 ans, stack st, 천의 자리를 확인할 cnt를 선언 후 적절히 초기화해줍니다.

📔 풀이과정

1. n이 1234일 때 n의 오른쪽부터 왼쪽으로 for lloop를 수행하며 다음을 진행합니다.  1-1. stack에 넣으면 stack에 [4,3,2,1] 순으로 원소가 저장되게 됩니다.  1-2. 이 때 cnt를 1씩 증가시키면서 3의 배수일 때마다 '.'을 하나씩 추가로 st에 push해주면 [4,3,2,.,1] 됩니다.2. while loop를 수행하면서 st에 top을 ans 뒤에 붙여주고 pop해줍니다.

📔 정답 출력 | 반환

ans를 반환합니다.


📕 Code

📔 C++

class Solution {
public:
    string thousandSeparator(int n) {
        string str = to_string(n);
        string ans;
        stack <char> st;
        int cnt = 0;
        for(int i = str.size() - 1; i >= 0; i--) {
            char c = str[i];
            st.push(c);
            cnt++;
            if(cnt % 3 == 0 && i != 0) {
                st.push('.');
            }
        }
        while(st.size()) {
            ans += st.top();
            st.pop();
        }
        return ans;
    }
};

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