Binary linked list to integer

Binary linked list to integer

Problem solution (C++)

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;
    }
};

Icon

Insert picture description here

Detailed

  1. Get the head node:
    (You don't need to quote cur here, call head directly, and quote cur to make the code logic clearer)
  2. Traversal:
    (the first traversal to obtain the value of the first node, and then, perform operations)
    [traversal end condition: the value of the cur node is empty]
  3. return value

difficulty

  1. Master the calculation method of binary positive and negative sequence
    1>. Positive sequence:
    Example 1: 101
    ans = [(1*2)+0] 2+1
    Example 2: 10011
    ans = {[[(1
    2)+0] 2+ 0] 2+1} 2 + 1
    2>. Reverse order:
    Example 1: 101
    ans = 1
    (2^0) + 0
    (2^1) + 1
    (2^2)
    【Order from back to front】
  2. And this question is the method of applying the positive sequence to calculate the binary

statement

  1. Author: ELE
  2. <Do not reprint without permission, welcome everyone to comment>

Guess you like

Origin blog.csdn.net/weixin_48557384/article/details/109251666