Replace All 0 Digits with 1 in an Integer: Python, C and Java
Three approaches to replace every 0 digit with 1 in an integer: string conversion, digit extraction loop, and edge cases. Code in Python, C, and Java.
Replacing every 0 digit with 1 in a given integer has two clean implementations: a string-conversion one-liner and a digit-extraction loop.
Both solve the same problem. The string approach is shorter; the digit-extraction approach works on the number directly without converting it to another type. Placement coding rounds at TCS, Infosys, and Wipro use this problem to test whether a candidate knows the modulo-10 digit pattern, the same building block behind Armstrong number checks, digit sums, and palindrome tests.
The Problem and Worked Examples
Given a non-negative integer, replace every digit 0 with 1 and return the result.
Worked examples (verified digit-by-digit):
- Input: 102405
- Digits: 1, 0, 2, 4, 0, 5
- After replacement: 1, 1, 2, 4, 1, 5
- Output: 112415
- Input: 56004
- Digits: 5, 6, 0, 0, 4
- After replacement: 5, 6, 1, 1, 4
- Output: 56114
- Input: 50307
- Digits: 5, 0, 3, 0, 7
- After replacement: 5, 1, 3, 1, 7
- Output: 51317
- Input: 0
- The input is the digit 0 itself.
- Output: 1
- Input: 5
- No zeros present.
- Output: 5 (unchanged)
Approach 1: String Conversion
Convert the integer to a string, replace every '0' character with '1', then convert back to an integer. The Python 3 str.replace method does the character swap in one call.
Python
def replace_zeros_string(n):
return int(str(n).replace('0', '1'))
# Test cases
print(replace_zeros_string(102405)) # 112415
print(replace_zeros_string(56004)) # 56114
print(replace_zeros_string(0)) # 1
print(replace_zeros_string(5)) # 5
C
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int replaceZerosString(int n) {
char buf[20];
sprintf(buf, "%d", n);
for (int i = 0; buf[i] != '\0'; i++) {
if (buf[i] == '0') {
buf[i] = '1';
}
}
return atoi(buf);
}
int main() {
printf("%d\n", replaceZerosString(102405)); // 112415
printf("%d\n", replaceZerosString(56004)); // 56114
printf("%d\n", replaceZerosString(0)); // 1
return 0;
}
Java
public class ReplaceZeros {
public static int replaceZerosString(int n) {
return Integer.parseInt(String.valueOf(n).replace('0', '1'));
}
public static void main(String[] args) {
System.out.println(replaceZerosString(102405)); // 112415
System.out.println(replaceZerosString(56004)); // 56114
System.out.println(replaceZerosString(0)); // 1
}
}
The string approach is the shortest path. Its trade-off: it allocates a string object on every call. For repeated calls in a tight loop, the object creation adds overhead. The digit-extraction approach below avoids this.
Approach 2: Digit Extraction with Modulo Division
Extract each digit from right to left using the modulo-10 loop. If the digit equals 0, replace it with 1. Reconstruct the number by accumulating digits multiplied by their positional weights.
Algorithm steps:
- Step 1: Handle the special case where n equals 0. Return 1 immediately.
- Step 2: Initialise
result = 0andplace = 1. - Step 3: While n is greater than 0, extract the last digit with
digit = n % 10. - Step 4: If
digit == 0, setdigit = 1. - Step 5: Add
digit * placetoresult, multiplyplaceby 10, then setn = n // 10. - Step 6: Return
result.
Trace for input 102405:
- Iteration 1: digit = 102405 % 10 = 5, place = 1, result = 5; n = 10240
- Iteration 2: digit = 10240 % 10 = 0, replace with 1; result = 5 + 1 * 10 = 15; n = 1024
- Iteration 3: digit = 1024 % 10 = 4; result = 15 + 4 * 100 = 415; n = 102
- Iteration 4: digit = 102 % 10 = 2; result = 415 + 2 * 1000 = 2415; n = 10
- Iteration 5: digit = 10 % 10 = 0, replace with 1; result = 2415 + 1 * 10000 = 12415; n = 1
- Iteration 6: digit = 1 % 10 = 1; result = 12415 + 1 * 100000 = 112415; n = 0
- Loop exits. Return 112415. Correct.
Python
def replace_zeros_math(n):
if n == 0:
return 1
result = 0
place = 1
while n > 0:
digit = n % 10
if digit == 0:
digit = 1
result += digit * place
place *= 10
n //= 10
return result
# Test cases
print(replace_zeros_math(102405)) # 112415
print(replace_zeros_math(56004)) # 56114
print(replace_zeros_math(1000)) # 1111
print(replace_zeros_math(0)) # 1
C
#include <stdio.h>
int replaceZerosMath(int n) {
if (n == 0) return 1;
int result = 0;
int place = 1;
while (n > 0) {
int digit = n % 10;
if (digit == 0) digit = 1;
result += digit * place;
place *= 10;
n /= 10;
}
return result;
}
int main() {
printf("%d\n", replaceZerosMath(102405)); // 112415
printf("%d\n", replaceZerosMath(56004)); // 56114
printf("%d\n", replaceZerosMath(1000)); // 1111
printf("%d\n", replaceZerosMath(0)); // 1
return 0;
}
Java
public class ReplaceZeros {
public static int replaceZerosMath(int n) {
if (n == 0) return 1;
int result = 0;
int place = 1;
while (n > 0) {
int digit = n % 10;
if (digit == 0) digit = 1;
result += digit * place;
place *= 10;
n /= 10;
}
return result;
}
public static void main(String[] args) {
System.out.println(replaceZerosMath(102405)); // 112415
System.out.println(replaceZerosMath(56004)); // 56114
System.out.println(replaceZerosMath(1000)); // 1111
System.out.println(replaceZerosMath(0)); // 1
}
}
This modulo-10 loop pattern is used in the Armstrong number check (another placement coding favourite), where each digit is extracted, raised to a power, and accumulated. The loop structure is identical; only the inner operation changes.
Edge Cases and Boundary Inputs
Three inputs need explicit handling:
- n = 0: The digit-extraction loop condition
n > 0is false from the start. Addif n == 0: return 1as the first line. The string approach handles this automatically sincestr(0)gives'0', whichreplaceconverts to'1'. - n = 1000 (or any number ending in zeros): Trailing zeros are extracted as the digit 0 and replaced with 1. Output for 1000 is 1111. The modulo loop handles this correctly without special-casing.
- n with no zeros (e.g., 5, 1234, 9999): The loop runs normally; no substitution happens; the output equals the input. No special case needed.
A common mistake is forgetting the n == 0 guard in the digit-extraction version. Without it, the while loop never executes and the function returns 0 instead of 1.
Time and Space Complexity
| Approach | Time | Space |
|---|---|---|
| String conversion | O(d) | O(d) — string buffer of d characters |
| Digit extraction | O(d) | O(1) — no auxiliary data structure |
Here d is the number of digits in the input. For a 32-bit signed integer the maximum d is 10 (the integer 2147483647 has 10 digits). Both approaches run in at most 10 iterations for any standard placement test input.
The digit-extraction approach uses O(1) extra space. The string conversion approach allocates a string of length d, making it O(d) space. For placement coding rounds the difference is immaterial; for interview discussions on a large-scale system, O(1) space is the correct answer to give.
For comparison, the matrix multiplication article in the same cluster covers O(m x n x p) time complexity for matrix operations, a useful contrast for understanding how digit-count loops sit at the shallow end of the complexity scale.
The digit-extraction loop pattern from this problem transfers directly to digit-sum problems, digital-root problems, and palindrome-number checks. Each uses the same digit = n % 10; n //= 10 skeleton with a different inner operation.
Once this modulo loop is second nature, the natural extension is writing programs that transform structured text inputs rather than integers: parsing output, extracting fields from API responses, rewriting tokens in a prompt. TinkerLLM is the place to practice that next step at ₹299, starting from the same pattern-recognition mindset this digit-replacement problem builds.
Primary sources
Frequently asked questions
What is the output when the input is 102405?
Every 0 digit is replaced with 1, giving 112415. Verified digit-by-digit: the digits 1, 0, 2, 4, 0, 5 become 1, 1, 2, 4, 1, 5, which form the number 112415.
What happens if the input itself is 0?
The digit-extraction loop exits immediately because 0 is not greater than 0. Add a special case at the start of the function: if n == 0, return 1. The string-conversion approach handles this automatically since '0' is replaced with '1'.
Why can't I use string conversion in placement tests?
Some online judges mark string-based solutions as incorrect for integer problems, categorising them as a type mismatch. The digit-extraction approach works on the number directly and is accepted across all judge configurations. When in doubt, implement both and switch if the judge rejects one.
How does the modulo-10 technique extract digits?
n modulo 10 gives the last digit of n. After processing that digit, integer-dividing n by 10 removes it. Repeating the loop processes each digit from right to left until n reaches zero.
What is the time complexity of both approaches?
Both run in O(d) time where d is the number of digits. For a 32-bit integer the maximum digit count is 10, so the loop runs at most 10 iterations. For all practical placement test inputs this is effectively constant-time.
Does this work for negative integers?
The standard problem assumes non-negative integers. For negative input, apply the replacement to the absolute value and restore the sign afterward. No common placement coding round includes negative inputs for this specific problem, but handling the case makes the solution production-grade.
A self-paced playground for building with LLMs.
TinkerLLM is FACE Prep's sister property. A guided environment for shipping real LLM applications, the kind of project that earns a paragraph on your resume, not a line.
Try TinkerLLM (₹299 launch)