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.
The linked list represents a binary number, with the most significant bit at the head. We can traverse the list, shifting the result left and adding the current node’s value at each step, effectively building the integer value bit by bit.
structListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(nullptr) {}
};
classSolution {
public:int getDecimalValue(ListNode* head) {
int ans =0;
while (head) {
ans = (ans <<1) | head->val;
head = head->next;
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
typeListNodestruct {
ValintNext*ListNode}
funcGetDecimalValue(head*ListNode) int {
ans:=0forhead!=nil {
ans = (ans<<1) | head.Valhead = head.Next }
returnans}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
classListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
classSolution {
publicintgetDecimalValue(ListNode head) {
int ans = 0;
while (head !=null) {
ans = (ans << 1) | head.val;
head = head.next;
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
dataclassListNode(var `val`: Int, var next: ListNode? = null)
classSolution {
fungetDecimalValue(head: ListNode?): Int {
var ans = 0var node = head
while (node !=null) {
ans = (ans shl 1) or node.`val`
node = node.next
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
classListNode:
def__init__(self, val: int =0, next: 'ListNode'=None):
self.val = val
self.next = next
classSolution:
defgetDecimalValue(self, head: ListNode) -> int:
ans =0while head:
ans = (ans <<1) | head.val
head = head.next
return ans