暴力解法:
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)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
原文:https://www.cnblogs.com/UjiMatca/p/14393019.html