[Leetcode] 1290. Convert Binary Number in a Linked List to Integer (C++)

마이구미·2021년 12월 7일
0

PS

목록 보기
56/69

문제

1290. Convert Binary Number in a Linked List to Integer

코드

class Solution {
public:
    int getDecimalValue(ListNode* head) {
        string s = "";
        int res = 0, exp = 0;
        
        while (head){
            s += to_string(head->val);
            head = head->next;
        }
        
        for (int i = s.size()-1; i >= 0; --i){
            res += pow(2, exp++) * (s[i] == '1' ? 1 : 0);
        }
        
        return res;
    }
};

접근

전체 연결리스트를 살펴보지 않는 이상 2진수를 알 수 없다. 따라서 연결리스트를 다 살펴보면서 2진수를 알아내고 이를 다시 10진수로 바꾸는 과정이 필요하다고 생각했다. 연결리스트를 순회하면서 2진수를 문자열로 저장하였는데 int 범위를 넘어설까에서 였다. 하지만 조건이 30자리라고 하니 큰 의미는 없었다. 후에 2진수를 10진수로 바꿀때는 뒤에서부터 하나씩 더해주었다.

profile
마이구미 마시쪙

0개의 댓글