LeetCode 1290. Convert Binary Number in a Linked List to Integer
考点 | 难度 |
---|---|
Linked List | Easy |
题目
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.
思路
每遇到一个新node
,把之前的值乘2再加上node
的值。乘以2等于bit manipulation中的把数字整个向左移动一位。
答案
public int getDecimalValue(ListNode head) {
int num = head.val;
while (head.next != null) {
num = num * 2 + head.next.val;
head = head.next;
}
return num;
}