-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReplaceZerosWithOnes.java
More file actions
42 lines (32 loc) · 1.22 KB
/
ReplaceZerosWithOnes.java
File metadata and controls
42 lines (32 loc) · 1.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import java.util.Scanner;
public class ReplaceZerosWithOnes {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Replace 0's with 1's");
System.out.println("-------------------");
System.out.print("Enter an integer: ");
int number = scanner.nextInt();
int result = replaceZerosWithOnes(number);
System.out.println("Input: " + number);
System.out.println("Output: " + result);
scanner.close();
}
private static int replaceZerosWithOnes(int number) {
// If number is 0, return 1
if (number == 0) {
return 1;
}
// For handling negative numbers
boolean isNegative = false;
if (number < 0) {
isNegative = true;
number = -number;
}
// Convert to string, replace zeros, and convert back to int
String numberStr = Integer.toString(number);
numberStr = numberStr.replace('0', '1');
int result = Integer.parseInt(numberStr);
// Return result with original sign
return isNegative ? -result : result;
}
}