aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJack Sangdahl <[email protected]>2025-07-13 21:16:55 -0600
committerJack Sangdahl <[email protected]>2025-07-13 21:16:55 -0600
commit4349ad85a06f47f84abbfbdb98427083ed5ca430 (patch)
tree9c2c0c6719578f39e6aef055d786be1b1287cbb4
parente608af56c0aba66323fb253f4bd2dfe3d2b38fb8 (diff)
downloadleetcode-4349ad85a06f47f84abbfbdb98427083ed5ca430.tar.gz
leetcode-4349ad85a06f47f84abbfbdb98427083ed5ca430.zip
1290. convert binary number in a linked list to integerHEADmaster
-rw-r--r--convert_bin_ll_int.c30
-rw-r--r--convert_bin_ll_int.py36
2 files changed, 66 insertions, 0 deletions
diff --git a/convert_bin_ll_int.c b/convert_bin_ll_int.c
new file mode 100644
index 0000000..308b204
--- /dev/null
+++ b/convert_bin_ll_int.c
@@ -0,0 +1,30 @@
+// 1290. Convert Binary Number in a Linked List to Integer
+#include "leetcode.h"
+
+/*
+ * 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. the most significant bit is at the head of the linked list.
+ */
+
+int getDecimalValue(struct ListNode *head) {
+ int ans = 0;
+ while (head) {
+ ans <<= 1;
+ ans += head->val;
+ head = head->next;
+ }
+ return ans;
+}
+
+int main() {
+ struct ListNode *h1 = listnode_create(1);
+ h1->next = listnode_create(0);
+ h1->next->next = listnode_create(1);
+ struct ListNode *h2 = listnode_create(0);
+ printf("%d\n", getDecimalValue(h1)); // expect: 5
+ printf("%d\n", getDecimalValue(h2)); // expect: 0
+ listnode_free(h1);
+ listnode_free(h2);
+}
diff --git a/convert_bin_ll_int.py b/convert_bin_ll_int.py
new file mode 100644
index 0000000..316dd4b
--- /dev/null
+++ b/convert_bin_ll_int.py
@@ -0,0 +1,36 @@
+# 1290. Convert Binary Number in a Linked List to Integer
+
+"""
+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. the most significant bit is at the head of the linked list.
+"""
+
+
+# Definition for singly-linked list.
+class ListNode(object):
+ def __init__(self, val=0, next=None):
+ self.val = val
+ self.next = next
+
+
+class Solution(object):
+ def getDecimalValue(self, head):
+ """
+ :type head: Optional[ListNode]
+ :rtype: int
+ """
+ ans = 0
+ while head:
+ ans = 2 * ans + head.val
+ head = head.next
+ return ans
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ h1 = ListNode(1, ListNode(0, ListNode(1)))
+ h2 = ListNode(0)
+ print(obj.getDecimalValue(h1))
+ print(obj.getDecimalValue(h2))