Convert Binary Number in a Linked List to Integer

PHOTO EMBED

Thu Jun 16 2022 12:18:12 GMT+0000 (Coordinated Universal Time)

Saved by @Ranjan_kumar #c++

/**
 * 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) 
    {
Method 1;
       int count=0;
       int sum=0;
       ListNode *temp=head;
       while(temp!=NULL)
       {
           count++;
               temp=temp->next;
       }
        ListNode *temp2=head;
        while(temp2!=NULL)
        {
            sum+= temp2->val*pow(2,(count-1));
            temp2=temp2->next;
            count--;
        }
        return sum;
Method 2;
        int ans = 0;
        while(head)
        {
            ans = ans*2+head->val;
            head = head->next;
        }
        return ans;
    }
};
content_copyCOPY