1290.二进制链表转整数

1290.二进制链表转整数


题目链接:1290.二进制链表转整数

代码如下:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
	int getDecimalValue(ListNode* head) {
		ListNode* p = head;
		int res = 0;
		while (p != nullptr) {
			res = res * 2 + p->val; // 将链表中的值转换为二进制
			p = p->next; // 移动到下一个节点
		}
		return res;
	}
};

你可能感兴趣的:(leetcode,c++)