模拟二进制转十进制就好了
借助栈是为了从最低位开始处理,借助左移运算符,左移一位相当于乘以2的1次幂,即x<<1 相当于x乘以2的1次幂。
struct ListNode
{
int val;
ListNode *next;
ListNode(int x):val(x),next(nullptr) {}
};
class Solution {
public:
int getDecimalValue(ListNode *head) {
stack<int> sta;
ListNode *cur = head;
while(cur) {
sta.push(cur->val);
cur = cur->next;
}
int ans = 0,e = 0;
while(!sta.empty()) {
int t = sta.top();
sta.pop();
t = t << e; //左移e位
ans += t;
e++;
}
return ans;
}
};