1.题目
2.解题思路
先遍历一遍链表,获取链表长度,然后从最高位开始计算
3.代码实现
class Solution {
public int getDecimalValue(ListNode head) {
ListNode temp = head;
int count = 0, sum = 0;
while(temp != null) {
temp = temp.next;
count++;
}
temp = head;
for (int i = 0; i < count; i++) {
sum += temp.val*Math.pow(2, count - 1 - i);
temp = temp.next;
}
return sum;
}
}
4.另一种二进制转十进制求法
可以一边遍历一边求,上一种解法需要遍历两次
ans = ans * 2 + cur->val;