Skip to content

LeetCode: 1290-Convert Binary Number in a Linked List to Integer

Last Updated on 2021-12-07 by Clay

題目

Given head which is a reference node to a singly-linked list. The value of each node in the linked list is either 0 or 1. The linked list holds the binary representation of a number.

Return the decimal value of the number in the linked list.

這個是比較單純的題目,有個二進制的數值使用鏈結串列(Linked List)表示,而我們要將其轉為十進制並回傳該數值。


解題思路

由於鏈結串列是從最大的位數開始計算起,而我們又不確定這個鏈結串列到底有幾位數,所以我們只能每次讀取進一個位數時,就將原本的數值全部乘以 2;這是因為二進制進位時就是乘以 2,跟十進制 100 變成 1000 時就是乘以 10 是同樣的道理。


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 ans = 0;
        
        while (head != NULL) {
            ans *= 2;            
            ans += head->val;
            head = head->next;
        }
        
        return ans;
    }
};



Python 範例程式碼

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def getDecimalValue(self, head: ListNode) -> int:
        ans = 0;
        
        while head != None:
            ans *= 2
            ans += head.val
            head = head.next
        
        return ans
        

References


Read More

Leave a Reply