I have create a function int reverseNum(Node *head)
to get number from reverse linked list.
eg. for Linked List:- 1->2->3->4 the number will be 4321.
But the program is returning 4320.
#include <bits/stdc++.h>
#define vi vector<int>
using namespace std;
struct Node {
int data;
Node *next;
Node(int x,Node *n){
data=x;
next=n;
}
Node(int x){
data=x;
next=nullptr;
}
};
//arr to LL
Node *arrToLL(vector<int> &arr){
//chk if the arr is empty
if (arr.empty()){
return nullptr;
}
Node *head=new Node(arr[0]);
Node *tmp=head;
for (int i=1;i<arr.size();i++){
Node *newNode=new Node(arr[i]);
tmp->next=newNode;
tmp=newNode;
}
return head;
}
//get reverse number from the LL
int reverseNum(Node *head){
int ans=0;
int exp=0;
while (head!=nullptr){
ans += (head->data * pow(10, exp));
cout<<ans<<"-";
exp++;
head=head->next;
}
return ans;
}
int main(){
vi arr1={1,2,3,4};
vi arr2={3,5,6};
Node *head1=arrToLL(arr1);
Node *head2=arrToLL(arr2);
cout<<reverseNum(head1);
return 0;
}
The pow
function returns a double
type, as it uses floating point algorithmic. This can lead to imprecisions, like occurred for the user that asked Why does pow(n,2) return 24 when n=5, with my compiler and OS?.
You should not need to rely on floating point calculations for this. Instead of exp
, use a variable that has the power you need, and which multiplies by 10 in each iteration:
int reverseNum(Node *head){
int ans=0;
int power=1; // <---
while (head!=nullptr){
ans += head->data * power; // <---
cout<<ans<<"-";
power *= 10; // <---
head=head->next;
}
return ans;
}
Now there is no floating point processing in your code anymore and the output will be as expected.
NB: be aware that the linked list data structure could hold many more digits than int
can represent. You will still get wrong results for linked lists that have like 30 digits.