給你一個(gè)單鏈表的引用結(jié)點(diǎn) head
。鏈表中每個(gè)結(jié)點(diǎn)的值不是 0 就是 1。已知此鏈表是一個(gè)整數(shù)數(shù)字的二進(jìn)制表示形式。
請(qǐng)你返回該鏈表所表示數(shù)字的 十進(jìn)制值 。
示例 1:
輸入:head = [1,0,1] 輸出:5 解釋:二進(jìn)制數(shù) (101) 轉(zhuǎn)化為十進(jìn)制數(shù) (5)
示例 2:
輸入:head = [0] 輸出:0
示例 3:
輸入:head = [1] 輸出:1
示例 4:
輸入:head = [1,0,0,1,0,0,1,1,1,0,0,0,0,0,0] 輸出:18880
示例 5:文章來源:http://www.zghlxwxcb.cn/news/detail-625467.html
輸入:head = [0,0] 輸出:0
代碼如下:文章來源地址http://www.zghlxwxcb.cn/news/detail-625467.html
//方法一:
class Solution {
public:
int getDecimalValue(ListNode* head) {
int res=0;
ListNode* curr=head;
ListNode* prev=nullptr;
while(curr!=nullptr)//反轉(zhuǎn)鏈表
{
ListNode* temp=curr->next;
curr->next=prev;
prev=curr;
curr=temp;
}
int t=1;//2^0=1
curr=prev;//反轉(zhuǎn)之后的鏈表鏈表的頭部指向prev,此時(shí)讓prev指向curr,鏈表頭部為curr
while(curr!=nullptr)
{
res+=t*curr->val;
t*=2;//2^0 2^1 2^2每次都是2倍
curr=curr->next;
}
return res;//返回最終結(jié)果
}
};
//方法二:
class Solution {
public:
int getDecimalValue(ListNode* head) {
int res=0;//記錄最終結(jié)果
ListNode* curr=head;
while(curr!=nullptr)
{
res=res*2+curr->val;//就相當(dāng)于十進(jìn)制數(shù)526=52*10+6,此時(shí)是二進(jìn)制數(shù)
curr=curr->next;
}
return res;
}
};
到了這里,關(guān)于二進(jìn)制鏈表轉(zhuǎn)整數(shù)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!