附leetcode链接:https://leetcode.com/problems/convert-binary-number-in-a-linked-list-to-integer/
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.
public class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
public int getDecimalValue(ListNode head) {
int value = 0;
while(head != null) {
value = (value<<1)|head.val;
head = head.next;
}
return value;
}
小结:二进制链表转化为十进制数字
这里使用了左移一位,并和当前值(按位或 | )
|按位或和&按位与计算方式都是转换二进制再计算,不同的是运算规则(一个为真即为真)1|0 = 1 , 1|1 = 1 , 0|0 = 0 , 0|1 = 1