首页 > 编程语言 > 详细

每日Leetcode-链表-算法-简单-二进制链表转整数

时间:2021-02-09 17:56:16      阅读:24      评论:0      收藏:0      [点我收藏+]

暴力解法:
1.第一次遍历链表,确定结点个数
2.第二次遍历链表,使每个结点乘对应权重

class Solution {
public:
    int getDecimalValue(ListNode* head) {
        ListNode* phead1 = head;
        ListNode* phead2 = head;
        int i,sum = 0;
        while(phead1 != nullptr)
        {
            phead1 = phead1->next;
            i++;
        }
        for(int j=i-1;j>=0;j--)
        {
            sum += pow(2,j) * phead2->val;
            phead2 = phead2->next;
        }
        return sum;
    }
};

执行出错:

Line 22: Char 17: runtime error: inf is outside the range of representable values of type ‘int‘ (solution.cpp)
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior prog_joined.cpp:32:17

解决方案:
把sum的类型由int改为double

class Solution {
public:
    int getDecimalValue(ListNode* head) {
        ListNode* phead1 = head;
        ListNode* phead2 = head;
        int i = 0;
        double sum = 0;
        while(phead1 != nullptr)
        {
            phead1 = phead1->next;
            i++;
        }
        for(int j=i-1;j>=0;j--)
        {
            sum += pow(2,j) * phead2->val;
            phead2 = phead2->next;
        }
        return sum;
    }
};

优化方案:
两次遍历太麻烦了,如果能一次遍历得出结果就好了,关键点在于权重的确定,下面是官方题解

class Solution {
public:
    int getDecimalValue(ListNode* head) {
        ListNode* cur = head;
        int ans = 0;
        while (cur != nullptr) {
            ans = ans * 2 + cur->val;
            cur = cur->next;
        }
        return ans;
    }
};

作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/convert-binary-number-in-a-linked-list-to-integer/solution/er-jin-zhi-lian-biao-zhuan-zheng-shu-by-leetcode-s/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

每日Leetcode-链表-算法-简单-二进制链表转整数

原文:https://www.cnblogs.com/UjiMatca/p/14393019.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!