[Classic reverse thinking] Binary to decimal conversion from high to low
Source of the problem:
The answer given by leetcode:
class Solution {
public:
int getDecimalValue(ListNode* head) {
ListNode* cur = head;
int ans = 0;
while (cur != nullptr) {
ans = ans * 2 + cur->val;
cur = cur->next;
}
return ans;
}
};
The main doubts to be resolved:
while (cur != nullptr) {
ans = ans * 2 + cur->val;
cur = cur->next;
}
How can such a simple two lines of code convert binary to decimal?
When we convert from binary to decimal, the general thinking is to convert from low to high, but obviously this question is to convert from high to low, then the question is how to convert from high to low?
Because typing the formula is too cumbersome, I used the above figure to explain the method of converting from high to low when converting binary to decimal. I think it should be explained clearly. If you have any questions, please leave a message in the comment area. Criticisms and corrections are welcome!