20.4.24 二进制链表转整数 简单 1290

解题思路

  1. 代码很短能看懂,主要是第一次接触到位运算,左移乘2,右移除2.

代码

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    int getDecimalValue(ListNode* head) {
        int sum=0;
        ListNode *curr=head;
        while(curr){
            sum=sum*2+curr->val;
            curr=curr->next;
        }
        return sum;
    }
};

猜你喜欢

转载自www.cnblogs.com/wasi-991017/p/12767657.html