Loading

【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. 

Example 1:

Input: head = [1,0,1]
Output: 5
Explanation: (101) in base 2 = (5) in base 10

     这道题的意思是,存在这样一个链表,链表中只存储0、1的数值,现在从头节点开始遍历到尾节点,将01二进制的数值转换成十进制。

/**
 * 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 {
public:
    int getDecimalValue(ListNode* head) {
        ListNode* node=head;
        int res=0;
        while(node){
            res=res*2+node->val;
            node=node->next;
        }
        return res;
    }
};
posted @ 2021-12-07 23:09  aalanwyr  阅读(52)  评论(0编辑  收藏  举报