Replace all 0’s with 1 in a given integer using Java

Replace all 0’s with 1 in a given integer using java  : 

In this article we will create a java program to replace all 0’s with 1 in a given integer. For this purpose we will ask the user to enter a positive number and check each digit one by one that it is equal to 0 or not. If the digit is equal to 0 then replace the digit by 1, and else no change.

For better understanding an example is shown in the diagram. 

Replace all 0's with 1 in a given integer using Java

Working :

Step 1 : Ask the user to enter a positive integer and store the value in a variable.

Step 2 : Convert the integer to string by using toString() function and then calculate the length. 

Step 3 : Declare a string variable to store the replaced number.

Step 4 : Use a loop from 0 till length of the string and increment the value of the loop by 1 in every iteration.

Step 5 : Use a condition for checking that the character at index i (where i is the value of the loop) is equal to 0 or not. If it is equal to 0 then convert it to 1 and else do not make any change

Step 6 : Repeat the steps 4 and 5 till the condition of the loop does not get false.

Step 7 : Print the replaced string.

Code in Java :

//Java program to replace all 0's with 1 in a given integer  : 
import java.util.Scanner;
public class replace_0_to_1
{
public static void main(String[] args)
{
//scanner class declaration
Scanner sc = new Scanner(System.in);
//input from the user
System.out.print("Enter the number : ");
int number = sc.nextInt();
//convert the number to string and then calculate its length
String str = Integer.toString(number);
int len = str.length();
String str1 = "";
//use the logic to replace all 0's with 1 in a given integer
for(int i = 0 ; i < len ; i++)
{
if(str.charAt(i) == '0')
str1 = str1 + '1';
else
str1 = str1 + str.charAt(i);
}
System.out.println("Output : "+str1);
//closing scanner class(not compulsory, but good practice)
sc.close();
}
}

Output :

Enter the number : 5002
Output : 5112


Enter the number : 51004040
Output : 51114141

Please Login/Signup to comment