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

## Replace all 0’s with 1 using Java

In this article we will create a  program to replace all 0’s with 1 using java. 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.

### Implementation

• We will convert the integer into string.
• Then we will convert it into list and then we will traverse through the list.
• Wherever we find a ‘0’ we will replace with ‘1’.

### Algorithm

• Take Input in num and initialize a variable num with with value 0
• If num is equals to zero then update the value of num2 to 1
• Iterate using a while loop until num is greater then 0
• For each iteration initialize a variable rem and store unit digit of num
• If rem equals to 0 then set rem to 1
• Set num to num divide by 10 & num2 equals to num2*10+rem
• Reverse and print num2

### Java code

Run
```//Java program to replace all 0's with 1 in a given integer  :
import java.util.Scanner;
public class Main
{
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("Converted number is: "+str1);
//closing scanner class(not compulsory, but good practice)
sc.close();
}
}```

### Output

```Enter the number : 706120678
Converted number : 716121678```

For similar question click on given button.

### 2 comments on “Replace all 0’s with 1 in a given integer using Java”

• Satendra

import java.util.*;public class Main
{
public static void main(String[] args)
{
String str=””;
String str2=””;
System.out.println(“enter”);
Scanner s= new Scanner(System.in);
str=s.nextLine();
for(int i=0; i<str.length();i++){
if(str.charAt(i)=='0'){
str2=str2+'1';

}
else{
str2=str2+str.charAt(i);

}

}
System.out.println(str2);
}
}

• Asif

import java.util.*;

public class Main
{
static int replace(int number)
{
// Base case for recursion termination
if (number == 0)
return 0;
// Extract the last digit and change it if needed
int digit = number % 10;
if (digit == 0)
digit = 1;
// Convert remaining digits and append the last digit
return replace(number/10) * 10 + digit;
}
static int Convert(int number)
{
if (number == 0)
return 1;
else
return replace(number);
}

public static void main(String[] args)
{
int number;
Scanner sc = new Scanner(System.in);
System.out.print(“Enter the number : “);
number = sc.nextInt();
System.out.print(“Number after replacement : “);
System.out.print(replace(number));
}
}