[Oracle] LeetCode 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.
Solution
点击查看代码
/**
* 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 {
private:
int ans=0;
int bs=1;
public:
int getDecimalValue(ListNode* head) {
if(!head)return 0;
while(head){
ans=2*ans+head->val;head=head->next;
}
return ans;
}
};