LeetCode Entry

1290. Convert Binary Number in a Linked List to Integer

14.07.2025 easy 2025 kotlin rust

Binary linked list to decimal

1290. Convert Binary Number in a Linked List to Integer easy blog post substack youtube

1.webp

Join me on Telegram

https://t.me/leetcode_daily_unstoppable/1049

Problem TLDR

Binary linked list to decimal #easy #linkedlist

Intuition

x = x * 2 + value

  • use recursion
  • use loop
  • use values to hold some data

Approach

  • try to write it in all difference ways

Complexity

  • Time complexity: \(O(n)\)

  • Space complexity: \(O(1)\)

Code


// 128ms
    fun ListNode?.str(): String = if (this == null) ""
        else "" + `val` + next.str()
    fun getDecimalValue(head: ListNode?) = head.str().toInt(2)


// 0ms
    fun getDecimalValue(head: ListNode?): Int =
        if (head?.next == null) head!!.`val` else
        getDecimalValue(head.next!!.apply { `val` += 2 * head.`val`})


// 0ms
    fun getDecimalValue(head: ListNode?, r: Int = 0): Int =
        head?.run { getDecimalValue(next, r * 2 + `val`) } ?: r


// 0ms
    fun getDecimalValue(head: ListNode?): Int {
        var x = head; var y = 0
        while (x != null) { y = y * 2 + x.`val`; x = x.next }
        return y
    }


// 0ms
    var max = 1
    fun getDecimalValue(head: ListNode?): Int = head?.run {
        val curr = max++
        getDecimalValue(next) + `val` * (1 shl (max - curr - 1))
    } ?: 0


// 0ms
    fun getDecimalValue(head: ListNode?): Int = head?.run {
        val curr = `val` / 2
        next?.`val` += (curr + 1) * 2
        val tail = getDecimalValue(next)
        val max = max(curr, (next?.`val` ?: 0) / 2)
        `val` = `val` % 2 + max * 2
        (`val` % 2) * (1 shl (max - curr)) + tail
    } ?: 0


// 0ms
    pub fn get_decimal_value(mut head: Option<Box<ListNode>>) -> i32 {
        let mut r = 0;
        while let Some(b) = head {
            r = r * 2 + b.val;
            head = b.next
        } r
    }


// 0ms
    int getDecimalValue(ListNode* head) {
        for (;; head = head->next)
            if (!head->next) return head->val;
            else head->next->val += head->val * 2;
    }