在 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