題目

將Linked List內的Binary Number讀取出來,轉換成Integer

解題方法

先將Linked List內容讀取出來存放在Vector中,再將其轉成數字即可

程式碼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public:
int getDecimalValue(ListNode* head) {
vector<int> tmp = load(head);
int ans = 0;
reverse(tmp.begin(),tmp.end());

for(int i=0;i<tmp.size();++i)
ans += tmp[i]*pow(2,i);

return ans;
}
vector<int> load(ListNode* &node)
{
vector<int> res;
while(node != nullptr)
{
res.push_back(node->val);
node = node->next;
}

return res;
}
};