본문 바로가기

Algorithm/Implementation

(C++) - LeetCode (easy) 168. Excel Sheet Column Title

반응형

https://leetcode.com/problems/excel-sheet-column-title/description/

 

Excel Sheet Column Title - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

진법 구현 문제였습니다.

📕 풀이방법

📔 풀이과정

* alphabat형태로 자릿수가 늘어나므로 26진법이라고 생각 해봅시다.

1. 'A'가 1부터 시작하므로 0부터 시작하는 진법을 맞추기 위해 -1한 값의 26으로 나눈 나머지를 vector v에 push_back해줍니다.

2. 구한 배열 v를 뒤집어줍니다.

3. v의 원소를 따라 순회하며 char로 바꿔주면서 정답 변수 ans에 문자를 연결해줍니다.


📕 Code

📔 C++

class Solution {
public:
    string convertToTitle(int columnNumber) {
        vector <int> v;
        while(columnNumber) {
            v.push_back(--columnNumber % 26);
            columnNumber /= 26;
        }
        reverse(v.begin(), v.end());
        string ans;
        for(auto e : v) ans += e + 'A';
        return ans;
    }
};

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