본문 바로가기

Algorithm/Implementation

(C++) - LeetCode (easy) 504. Base 7

반응형

https://leetcode.com/problems/base-7/description/

 

Base 7 - LeetCode

Can you solve this real interview question? Base 7 - Given an integer num, return a string of its base 7 representation.   Example 1: Input: num = 100 Output: "202" Example 2: Input: num = -7 Output: "-10"   Constraints: * -107 <= num <= 107

leetcode.com

7진법 구현 문제였습니다.

📕 풀이방법

📔 입력 및 초기화

부호를 제거한 num값을 저장할 변수 tmp, 정답을 반환할 ans를 선언해줍니다.

📔 풀이과정

1. num이 0인 경우 정답은 0입니다

2. 나머지의 경우에 tmp를 7진법으로 변환 후 문자로 바꿔 ans에 저장합니다. ans는 좌우가 반전된 문자열이므로 마지막에 -를 붙일지 여부를 판단해 붙인뒤 reverse함수를 사용해 뒤집어 줍니다.

📔 정답 출력 | 반환

ans를 반환합니다.


📕 Code

📔 C++

class Solution {
public:
    string convertToBase7(int num) {
        if(!num) return "0";
        int tmp = num < 0 ? -num : num;
        string ans;
        
        while(tmp) {
            ans += to_string(tmp%7);
            tmp /= 7;
        }
        
        if(num < 0) ans += "-";
        reverse(ans.begin(), ans.end());
        return ans;
    }
};

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