/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public int getDecimalValue(ListNode head) {
List arr = new ArrayList<Integer>();
while(head != null){
arr.add(head.val);
head = head.next;
}
System.out.println(arr);
int sum = 0;
int val = 1;
for(int j=arr.size() - 1; j>=0; j--){
sum += (Integer)(arr.get(j)) *val;
val = val*2;
}
return sum;
}
}
需要注意两个地方:
1、在Java中 ^符合不是平方,导致出错,所以每次都需要乘2.
2、一开始声明成了数组arr,但数组的长度需要指定,长度是固定的,没有数值会自动填充为0,导致计算出错。