C++ Program to Replace all 0’s with 1 in a given integer

Program to Replace all 0’s with 1 in a given integer

Here we will discuss how to replace all the 0’s with 1 in a given integer using C++ programming language.

The concept is simple, find the digits of the integer. Compare each digit with 0 if the digit is equal to 0 then replace it with 1.

Construct the new integer with the replaced digits.

Replace all 0’s with 1 in C++

Algorithm:-

  1. User gives an input.
  2. The input is stored in an int type variable say num.
  3. A loop is started
    1. Digits of the num is founded and stored in another variable say rem

                      int rem = num%10;

                2. Each digit is compared with 0

      1. If the digit is equal to 0 then replace it with 1

                              if(rem == 0)

                              rem = 1;

                3. Construct the new number digit by digit.

                     new=new*10+rem;

      4. Print the output.

Replace all 0's with 1 in a given integer

C++ Code:-

    //Convert all 0's to 1

   #include<iostream>

    using namespace std;

    //main program

    int main()

    {

        int num,num2=0;

        cout<<"Enter number: ";

        //user input

        cin>>num;

        //checking for 0 input

        if(num == 0)

            num2=1;

        //converting 0 to 1

        while(num>0)

        {

            int rem = num%10;

            if(rem == 0)

                rem = 1;

            num = num/10;

            num2=num2*10+rem;

        }

       num = 0 ; // Store the reverse of num2

       while(num2>0){

        int r = num2%10;

      num= num*10 + r;

      num2 /= 10;

    }

        //converted number

        cout<<"Converted number is: "<<num;

        return 0;

    }
Output

Enter number: 101011

Converted number is: 111111

coding (3)

One comment on “C++ Program to Replace all 0’s with 1 in a given integer”


  • Roshni

    //C++ Program
    //Convert all 0’s to 1
    #include
    using namespace std;
    //main program
    int main()
    {
    int num,num2=0,i=1;
    cout<>num;
    //checking for 0 input
    if(num == 0)
    num2=1;
    //converting 0 to 1
    while(num>0)
    {
    int rem = num%10;
    if(rem == 0)
    rem = 1;
    num = num/10;
    num2=num2+rem*i;
    i *=10;
    }
    //converted number
    cout<<"Converted number is: "<<num2;
    return 0;
    }