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.

Working

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

    int rem = num%10;

    • Each digit is compared with 0
      • If the digit is equal to 0 then replace it with 1

    if(rem == 0)

                       rem = 1;

    • Construct the new number digit by digit.

    new=new*10+rem;

  • Print the output.
Replace all 0’s with 1 in a given integer

C++ Code

//C++ Program
//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;
}
//converted number
cout<<"Converted number is: "<<num2;
return 0;
}

Output

Enter number: 101011
Converted number is: 111111

Please Login/Signup to comment