본문 바로가기

Algorithm/자료구조

(C++) - LeetCode (easy) 1290. Convert Binary Number in a Linked List to Integer

반응형

https://leetcode.com/problems/convert-binary-number-in-a-linked-list-to-integer/description/

 

LeetCode - The World's Leading Online Programming Learning Platform

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

자료구조 linked list를 이용한 문제였습니다.

📕 풀이방법

📔 입력 및 초기화

1. 정답 변수 decimal을 선언 후 0으로 초기화해줍니다.2. ListNode의 원소를 순회하기 위한 변수 cur를 선언해 head로 주소 초기화해줍니다.

📔 풀이과정

이진수는 오른쪽에서 왼쪽으로 갈수록 2의 승수가 증가합니다. 예를 들어, 이진수 101은 십진수로 변환하면1*2^2 + 0*2^1 + 1*2^0 = 4 + 0 + 1 = 5 가 됩니다. 이를 왼쪽부터 오른쪽 자리 수로 이진수를 읽으면서 누적해 처리하기 위해서는 ListNode를 순회하며 다음과 같이 하면 됩니다.1. decimal의 이전 값에 2를 곱합니다. 이는 list node의 마지막 원소를 확인했을 때 곱해진 2의 개수는 원래 십진수로 변환하는 방법(오른쪽에서 왼쪽으로 이동하면서 2의 승수 증가)와 같습니다.2. 이후 decimal에 현재 node 값 cur->val을 더합니다. 이는 현재 자릿수의 값을 추가하는 것과 같습니다.시간 복잡도는 O(1)로 빠르게 처리 가능합니다.

📔 정답 출력 | 반환

decimal값을 반환합니다.


📕 Code

📔 C++

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    int getDecimalValue(ListNode* head) {
        int decimal = 0;
        ListNode *cur = head;
        string num;
        while(cur != NULL) {
            decimal = decimal * 2 + cur->val;
            cur = cur -> next;
        }
        return decimal;
    }
};

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