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.
Input: head = [1,0,1]
Output: 5
Explanation: (101) in base 2 = (5) in base 10
把链表对应的二进制数转为十进制数,链表的head对应二进制数的最高位。
思路:
可能会想到用一个数组把数字都保存下来,然后从低位开始转换。但是这样space 和 time complexity都很高。
可以用二进制位运算解决,定义一个变量result。
从head读起,每往右读一位,result左移一位,同时与当前head.val取或,这相当于result*2 + head.val,直到head == null
public int getDecimalValue(ListNode head) {
if(head == null) {
return 0;
}
int result = 0;
while(head != null) {
result = result << 1 | head.val;
head = head.next;
}
return result;
}