Place or shift all zeros to the extreme right of a number in C++

In this tutorial, we will learn how to shift or place all zeros to the extreme right of a number in C++.

We can solve this problem in linear time complexity using String. So, let us see the approach first.

Approach :

First, we will store all the integers of the number in another string in the same sequence of its position in the number. Then, we will count the number of zeros present in the number. We will simply add that amount of zeros to the end of the new string. We will print the new string, that would be our New number.

Let us see an example,

01204005 is a number. We will store the non-zero integers in another new string. So the new string would be ‘1245’. Now we will count the zeros in the number, which is 4 here. We will simply append 4 zeros at the end of the new string. So, now the new string is ‘12450000‘.

C++ Code to place all zeros to the extreme right of a number in C++

Here is the code of the above approach.

#include <bits/stdc++.h>
using namespace std;

int main()
{
   char s[10001],s1[10001]={0};//size will be 10000(10^1000)
   cin>>s;// taking input of string
   long long int i,c=0,j=0;
   for(i=0;i<strlen(s);i++){
       if(s[i]!='0'){
           s1[j]=s[i];// store the non-zero integers in the new string s1
           j++;
       }
       else{
           c++;// cout the number of zeros present in the number
       }
   }
   for(i=0;i<c;i++){
        s1[j]='0';// append that no of zeros at the end of the new string
        j++;
   }
   cout<<s1<<"\n";// print the new string that is our desired result
}

//Input : 012000345
//Output : 123450000

Time Complexity :

The time complexity of this problem is O(n), where n is the length of the new string.

I hope you have enjoyed it. Thanks for reading the article !!!!

Also read:

Leave a Reply

Your email address will not be published. Required fields are marked *