使用php做的網站有哪些西安自助建站
給你一個單鏈表的引用結點 head
。鏈表中每個結點的值不是 0 就是 1。已知此鏈表是一個整數數字的二進制表示形式。
請你返回該鏈表所表示數字的 十進制值 。
示例 1:
輸入:head = [1,0,1] 輸出:5 解釋:二進制數 (101) 轉化為十進制數 (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:
輸入:head = [0,0] 輸出:0
代碼如下:
//方法一:
class Solution {
public:int getDecimalValue(ListNode* head) {int res=0;ListNode* curr=head;ListNode* prev=nullptr;while(curr!=nullptr)//反轉鏈表{ListNode* temp=curr->next;curr->next=prev;prev=curr;curr=temp;}int t=1;//2^0=1curr=prev;//反轉之后的鏈表鏈表的頭部指向prev,此時讓prev指向curr,鏈表頭部為currwhile(curr!=nullptr){res+=t*curr->val;t*=2;//2^0 2^1 2^2每次都是2倍curr=curr->next;}return res;//返回最終結果}
};//方法二:
class Solution {
public:int getDecimalValue(ListNode* head) {int res=0;//記錄最終結果ListNode* curr=head;while(curr!=nullptr){res=res*2+curr->val;//就相當于十進制數526=52*10+6,此時是二進制數curr=curr->next;}return res;}
};