Skip to content

← leetcode

Convert Binary Number in a Linked List to Integer

· Easy

LeetCode problem 1290

We can simply iterate through the linked list and left shift our answer after every iteration, adding 1 depending on what the bit is.

Using [0, 1, 0, 1] as an example, we have:

  • index 0 = 0 so 2 x 0 + 0 = 0 so u get 2^0 * 0
  • index 1 = 1 so 2 x 0 + 1 = 1 so u get 2^1 * 0 + 2^0 * 1
  • index 2 = 0 so 2 x 1 + 0 = 2 so u get 2^2 * 0 + 2^1 * 1 + 2^0 * 0
  • index 3 = 1 so 2 x 2 + 1 = 5 so u get 2^3 * 0 + 2^2 * 1 + 2^1 * 0 + 2^0 * 1

code

/**
 * 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;
    }
};

complexity

  • Time: O(n) where n is the length of the linked list with head
  • Space: O(1)

time taken

  • 4 minutes and 6 seconds