Leetcode. 1290 二进制链表转整数

题目

输入:head = [1,0,1] 输出:5 解释:二进制数 (101) 转化为十进制数 (5)

输入:head = [0,0] 输出:0

代码

法一、自己的笨法,逆置链表然后从原链表的尾节点开始相加

 1 class Solution {
 2 public:
 3     int getDecimalValue(ListNode* head) {
 4         //先考虑将链表进行逆置
 5         ListNode *pre = head; ListNode *cur = head->next;
 6         while(cur != NULL){
 7             ListNode *tmp = cur->next;
 8             cur->next = pre;
 9             pre = cur;
10             cur = tmp;
11         }
12         head->next = NULL;
13 
14         int sum = 0;int t = 1;
15         while(pre!=NULL){
16             sum += pre->val * t;
17             pre = pre->next;
18             t *= 2;
19         }
20 
21         return sum;
22     }
23 };

时间复杂度 O(n),空间复杂度O(1)

法二、大神级(运用反向操作,直接记住)

 1 class Solution {
 2 public:
 3     int getDecimalValue(ListNode* head) {
 4         ListNode* cur = head;
 5         int ans = 0;
 6         while (cur != nullptr) {
 7             ans = ans * 2 + cur->val;
 8             cur = cur->next;
 9         }
10         return ans;
11     }
12 };

猜你喜欢

转载自www.cnblogs.com/fresh-coder/p/13377304.html