1290二进制链表转整数
一个单链表引用节点head中,每个节点的值都是1或者0,
返回它所表示的十进制数。
我新手想的笨办法,先求得总的节点个数,结果用pow函数累加出来。
完整代码
int getDecimalValue(struct ListNode* head)
{
int n=1;
int num=0;
if(head==NULL)
return 0;
struct ListNode*h=head;
while(h->next!=NULL)
{
n++;//节点数
h=h->next;
}
int nn=n;
h=head;
while(h!=NULL)
{
num=num+(h->val)*pow(2,nn-1); //累加结果
nn--;
h=h->next;
}
return num;
}
完