Java Online Compiler
Example: Replace Zeros with Ones using Mathematical Operations in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Replace Zeros with Ones using Mathematical Operations import java.util.Scanner; // Main class containing the entry point of the program public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Step 1: Get integer input from the user System.out.print("Enter an integer: "); int originalNumber = scanner.nextInt(); // Handle the special case of 0 if (originalNumber == 0) { System.out.println("Original number: " + originalNumber); System.out.println("Modified number: 1"); // 0 becomes 1 scanner.close(); return; } int modifiedNumber = 0; int powerOfTen = 1; // Used to place digits in correct positions int tempNumber = originalNumber; // Step 2: Process the number digit by digit while (tempNumber > 0) { int digit = tempNumber % 10; // Get the last digit // Step 3: Replace 0 with 1 if found if (digit == 0) { digit = 1; } // Step 4: Reconstruct the modified number modifiedNumber = digit * powerOfTen + modifiedNumber; // Step 5: Move to the next digit and update power of ten tempNumber /= 10; powerOfTen *= 10; } // Step 6: Print the result System.out.println("Original number: " + originalNumber); System.out.println("Modified number: " + modifiedNumber); scanner.close(); } }
Output
Clear
ADVERTISEMENTS