[LeetCode] 1290. Convert Binary Number in a Linked List to Integer 二进制链表转整数
Given head
which is a reference node to a singly-linked list. The value of each node in the linked list is either 0
or 1
. The linked list holds the binary representation of a number.
Return the decimal value of the number in the linked list.
Example 1:
Input: head = [1,0,1]
Output: 5
Explanation: (101) in base 2 = (5) in base 10
Example 2:
Input: head = [0]
Output: 0
Constraints:
- The Linked List is not empty.
- Number of nodes will not exceed
30
. - Each node's value is either
0
or1
.
这道题让把一个用链表表示的二进制数转为一个整型数,链表的结点值只有0或1,而且首结点是二进制数的最高位。这题主要考察两点,一个是二进制数如何转十进制数,另一个是遍历链表。都不是太难,直接遍历链表,每次先将 res 自乘以2,因为新加一个结点,说明之前的每一位都要左移一位,所以要乘以2,然后再加上当前结点值,同时将 head 指针右移一位即可,参见代码如下:
class Solution {
public:
int getDecimalValue(ListNode* head) {
int res = 0;
while (head) {
res = res * 2 + head->val;
head = head->next;
}
return res;
}
};
Github 同步地址:
https://github.com/grandyang/leetcode/issues/1290
参考资料:
https://leetcode.com/problems/convert-binary-number-in-a-linked-list-to-integer/