본문 바로가기

Algorithm/Implementation

(C++) - LeetCode (easy) 405. Convert a Number to Hexadecimal

반응형

https://leetcode.com/problems/convert-a-number-to-hexadecimal/description/

 

Convert a Number to Hexadecimal - LeetCode

Can you solve this real interview question? Convert a Number to Hexadecimal - Given an integer num, return a string representing its hexadecimal representation. For negative integers, two’s complement [https://en.wikipedia.org/wiki/Two%27s_complement] me

leetcode.com

16진수 구현 문제였습니다.

📕 풀이방법

📔 입력 및 초기화

정답 ans와 16진수의 문자열 hexa, int 범위의 한계로 long long n을 선언해줍니다. 16진수는 10 ~ 15까지의 수가 a ~ f로 나타내지게 됩니다. 이에 맞게 hexa값을 초기화해줍니다. n은 암묵적 형변환으로 num값을 long long으로 저장해줍니다.

📔 풀이과정

1. 음수라면 2의 보수법으로 표현시 32 bit가 모두 켜져 있는 상태에서 n만큼 더해준 값이 됩니다. n이 음수라면 해당 변환을 적용해줍니다.

2. n  % 16이 가장 오른쪽 자리부터 채워질 자리수를 의미합니다. 해당 index를 hexa에 도입해 16진수에 해당하는 문자를 얻어옵니다. 그 문자를 ans 끝에 붙여줍니다. 매 자리마다 n을 16으로 나눠줌으로써 16진수로 표현된 뒤집어진 문자열이 ans에 저장되게 됩니다.

3. ans를 뒤집어줍니다.

📔 정답 출력 | 반환

ans를 반환합니다.


📕 Code

📔 C++

#define ll long long
class Solution {
public:
    string hexa = "0123456789abcdef"; 
    string toHex(int num) {
        ll n = num;
        string ans;
        if(!n) return "0";
        if(n < 0) {
            n = (1ull << 32) + n;
        }
        while(n) {
            ans += hexa[n % 16];
            n /= 16;
        }
        reverse(ans.begin(), ans.end());
        return ans;
    }
};

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