Consider a list of single digit numbers. For example, [2,2,5]. Consider the succ
ID: 3544857 • Letter: C
Question
Consider a list of single digit numbers. For example, [2,2,5]. Consider the successors of such lists. The successor of [2,2,5] is [2,2,6]. The successor of [2,3,9,9] is [2,4,0,0]. The successor of [9,9,9,9] is [1,0,0,0,0]. Write a program that takes such a list of numbers as input and returns its successor. You cannot express this list as a decimal number and compute its successor as the number may be so large that an overflow occurs. Make your program as short as possible. The list is defined as an array. Submit code in C++ along with compilation instructions and test scripts.
Explanation / Answer
#include<iostream>
using namespace std;
int main()
{
int n,arr[200],rem=0,i;
cout<<"enter the length of list : ";
cin>>n;
cout<<"enter the list: "<<endl;
for(i=0;i<n;i++)
cin>>arr[i];
arr[n-1]=arr[n-1]+1;
if(arr[n-1]==10)
{arr[n-1]=0;rem=1;
}
else
rem=0;
for(i=n-2;i>=0;i--)
{arr[i]=arr[i]+rem;
if(arr[i]<=9)
rem=0;
else if(arr[i]==10)
{
rem=1;arr[i]=0;
}
}
cout<<"the successor list is :"<<endl;
if(rem==1)
cout<<" 1 ";
for(i=0;i<n;i++)
cout<<arr[i]<<" ";
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.