链表的前面的节点是二进制数的高位,所以可以通过移位然后取或的方式来实现。
语言 Java:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public int getDecimalValue(ListNode head) {
int r = 0;
for(; head != null; head = head.next) {
r = (r << 1) | head.val;
}
return r;
}
}
语言 Golang:
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func getDecimalValue(head *ListNode) int {
r := 0
for ; head != nil; head = head.Next {
r = (r << 1) | head.Val
}
return r;
}