Skip to content

Commit 25690c9

Browse files
committed
Sync LeetCode submission Runtime - 0 ms (100.00%), Memory - 17.9 MB (26.17%)
1 parent 6ac5d90 commit 25690c9

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
<p>Given <code>head</code> which is a reference node to a singly-linked list. The value of each node in the linked list is either <code>0</code> or <code>1</code>. The linked list holds the binary representation of a number.</p>
2+
3+
<p>Return the <em>decimal value</em> of the number in the linked list.</p>
4+
5+
<p>The <strong>most significant bit</strong> is at the head of the linked list.</p>
6+
7+
<p>&nbsp;</p>
8+
<p><strong class="example">Example 1:</strong></p>
9+
<img alt="" src="https://assets.leetcode.com/uploads/2019/12/05/graph-1.png" style="width: 426px; height: 108px;" />
10+
<pre>
11+
<strong>Input:</strong> head = [1,0,1]
12+
<strong>Output:</strong> 5
13+
<strong>Explanation:</strong> (101) in base 2 = (5) in base 10
14+
</pre>
15+
16+
<p><strong class="example">Example 2:</strong></p>
17+
18+
<pre>
19+
<strong>Input:</strong> head = [0]
20+
<strong>Output:</strong> 0
21+
</pre>
22+
23+
<p>&nbsp;</p>
24+
<p><strong>Constraints:</strong></p>
25+
26+
<ul>
27+
<li>The Linked List is not empty.</li>
28+
<li>Number of nodes will not exceed <code>30</code>.</li>
29+
<li>Each node&#39;s value is either <code>0</code> or <code>1</code>.</li>
30+
</ul>
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
# Approach 2: Bit Manipulation
2+
3+
# Time: O(n)
4+
# Space: O(1)
5+
6+
# Definition for singly-linked list.
7+
# class ListNode:
8+
# def __init__(self, val=0, next=None):
9+
# self.val = val
10+
# self.next = next
11+
class Solution:
12+
def getDecimalValue(self, head: Optional[ListNode]) -> int:
13+
num = head.val
14+
while head.next:
15+
num = (num << 1) | head.next.val
16+
head = head.next
17+
18+
return num

0 commit comments

Comments
 (0)