題目地址:
https://leetcode.com/problems/convert-binary-number-in-a-linked-list-to-integer/
給定一個只由或構成的鏈表,返回其代表的二進制數。直接模擬就好了。代碼如下:
public class Solution {
public int getDecimalValue(ListNode head) {
int res = 0;
while (head != null) {
res <<= 1;
res += head.val;
head = head.next;
}
return res;
}
}
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
時間複雜度。