在 C++ 中將連結串列中的二進位制數轉換為整數
假設我們有一個“頭”,它是到單鏈表的引用節點。連結串列中每個節點的值要麼是 0,要麼是 1。此連結串列儲存數字的二進位制表示形式。我們需要返回連結串列中數字的十進位制值。因此,如果連結串列類似於 [1,0,1,1,0,1]
為解決此問題,我們將遵循以下步驟:
x:將連結串列元素轉換為陣列
然後反轉連結串列 x
ans:0,temp:1
對於 i(i:0 到 x 的大小 - 1)範圍
ans:ans + x[i] * temp
temp:temp * 2
返回 ans
示例(C++)
讓我們看看以下實現以獲取更好的理解:
#include <bits/stdc++.h>
using namespace std;
class ListNode{
public:
int val;
ListNode *next;
ListNode(int data){
val = data;
next = NULL;
}
};
ListNode *make_list(vector<int> v){
ListNode *head = new ListNode(v[0]);
for(int i = 1; i<v.size(); i++){
ListNode *ptr = head;
while(ptr->next != NULL){
ptr = ptr->next;
}
ptr->next = new ListNode(v[i]);
}
return head;
}
class Solution {
public:
vector <int> getVector(ListNode* node){
vector <int> result;
while(node){
result.push_back(node->val);
node = node->next;
}
return result;
}
int getDecimalValue(ListNode* head) {
vector <int> x = getVector(head);
reverse(x.begin(), x.end());
int ans = 0;
int temp = 1;
for(int i = 0; i < x.size(); i++){
ans += x[i] * temp;
temp *= 2;
}
return ans;
}
};
main(){
Solution ob;
vector<int> v = {1,0,1,1,0,1};
ListNode *head = make_list(v);
cout << ob.getDecimalValue(head);
}輸入
[1,0,1,1,0,1]
輸出
45
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP