Given
head
which is a reference node to a singly-linked list. The value of each node in the linked list is either 0 or 1. The linked list holds the binary representation of a number.Find the decimal value of the number in the linked list.
Example:
Input: 1->0->1->NULL
Output: 5
Approach
Java
public class ConvertBinaryNumberInLinkedList {public static void main(String[] args) {ListNode head = new ListNode(1);head.next = new ListNode(0);head.next.next = new ListNode(1);System.out.println(getDecimalValue(head));}static int getDecimalValue(ListNode head) {ListNode temp = head;ListNode curr;ListNode prev = null;while (temp != null) {curr = temp;temp = temp.next;curr.next = prev;prev = curr;}int i = 0;int ans = 0;ListNode temp1 = prev;while (temp1 != null) {if (temp1.val == 1)ans += Math.pow(2, i);i++;temp1 = temp1.next;}return ans;}}class ListNode {int val;ListNode next;ListNode() {}ListNode(int val) {this.val = val;}ListNode(int val, ListNode next) {this.val = val;this.next = next;}}
C++
#include <bits/stdc++.h>using namespace std;//Struture of nodestruct Node{int data;Node *next;Node(int data){this->data=data;this->next=NULL;}};int getDecimalValue(Node* head){Node *temp=head,*curr,*prev=NULL;while(temp!=NULL){curr=temp;temp=temp->next;curr->next=prev;prev=curr;}int i=0;int ans=0;Node *temp1=prev;while(temp1!=NULL){if(temp1->data==1)ans+=pow(2,i);i++;temp1=temp1->next;}return ans;}int main(){Node *head=new Node(1);head->next=new Node(0);head->next->next=new Node(1);cout<<getDecimalValue(head);return 0;}
No comments:
Post a Comment