链表_LeetCode_1290_二进制链表转整数
原题:给你一个单链表的引用结点 head。链表中每个结点的值不是 0 就是 1。已知此链表是一个整数数字的二进制表示形式。请你返回该链表所表示数字的 十进制值 。
链表定义:
struct ListNode { int val; struct ListNode *next; };
法一:数学
1 int getDecimalValue(struct ListNode* head){
ListNode* p = head; 5 int n = 0; 6 while (p != NULL) { 7 n = n * 2 + p->val; 8 p = p->next; 9 } 10 return n; 11 }
法二:位运算
int getDecimalValue(struct ListNode* head){ int n = 0; struct ListNode * p = head; while (p){ n = (n<< 1) | (p->val); p = p->next; } return n; }
法三:遍历两次,第一次记下最高项幂,第二次进行二进制计算。(第一遍做的silly法)
🛫️起飞

浙公网安备 33010602011771号