Task: Find the result after adding 1 to given an array of N non negative elements.
Example:
Input:
1
3
9 9 9
Output:
1 0 0 0
Here is the Code:
Program in C++:
- #include<iostream>
- using namespace std;
- void addingOne(int *a,int n)
- {
- int sum,carry=1;
- for(int i=n-1;i>=0;i--)
- {
- sum=a[i]+carry;
- if(sum>9)
- {
- a[i]=sum%10;
- carry=sum/10;
- }
- else
- {
- a[i]=sum;
- carry=0;
- break;
- }
- }
- if(carry!=0)
- {
- cout<<carry<<" ";
- }
- for(int i=0;i<n;i++)
- {
- cout<<a[i]<<" ";
- }
- }
- int main()
- {
- int t;
- cin>>t;
- while(t--)
- {
- int n;
- cin>>n;
- int a[n];
- for(int i=0;i<n;i++)
- {
- cin>>a[i];
- }
- addingOne(a,n);
- cout<<endl;
- }
- return 0;
- }
- /*
- // For updated version
- class Solution{
- public:
- vector<int> addOne(int a[], int n) {
- // code here
- int sum,carry=1;
- vector<int> b;
- for(int i=n-1;i>=0;i--)
- {
- sum=a[i]+carry;
- a[i]=sum%10;
- carry=sum/10;
- }
- if(carry!=0)
- {
- cout<<carry<<" ";
- }
- for(int i=0;i<n;i++)
- {
- b.insert(b.begin()+i,a[i]);
- }
- return b;
- }
- };
- */
Here is the Video:
Comments
Post a Comment