1290. Convert Binary Number in a Linked List to Integer

CODE Brute forces

class Solution { 
public:
    int getDecimalValue(ListNode* head) {
     if(head->next==NULL) return head->val;
        int length=0,result=0,i=0;
        ListNode* temp=head;
        while(temp->next){
            length++;
            temp=temp->next;
        }
        temp=head;
        while(temp->next){
            if(temp->val==1){
                result+=pow(2,(length-i));
            }
            i++;
            temp=temp->next;
        }
        if(temp->val==1)return result+1;
        else return result;
    }
};    
    

Optimize Solution

class Solution {
public:
    int getDecimalValue(ListNode* head) {
    int ans = 0;
    ListNode* temp = head;
    while(temp != NULL)
    {
        ans*=2;
        ans += (temp->val);
        temp = temp->next;
         }
    return ans;    
    }
};
Comments (1)