首页 > 数据库 >[Oracle] LeetCode 1290 Convert Binary Number in a Linked List to Integer

[Oracle] LeetCode 1290 Convert Binary Number in a Linked List to Integer

时间:2022-09-27 05:33:04浏览次数:66  
标签:Binary Convert ListNode int list List head next linked

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;
    }
};

标签:Binary,Convert,ListNode,int,list,List,head,next,linked
From: https://www.cnblogs.com/xinyu04/p/16733166.html

相关文章