题目链接
迭代:
class Solution {
public int getDecimalValue(ListNode head) {
int length=0;
ListNode p=head;
while(p!=null){
length++;
p=p.next;
}
p=head;
int sum=0;
int clength=length;
for(int i=0;i<length;i++){
int l=clength-1;
int cursum=1;
if(p.val==0){
sum+=0;
}
else{
while(l>0){
cursum*=2;
l--;
}
sum+=cursum;
}
clength--;
p=p.next;
}
return sum;
}
}
模拟恢复:
class Solution {
public int getDecimalValue(ListNode head) {
int ans=0;
ListNode p=head;
while(p!=null){
ans=ans*2+p.val;
p=p.next;
}
return ans;
}
}
模拟过程: