/** * 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; } };
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter