Iterative with Reversal
The function ‘replaceZeroWithFive’ iterates through each digit of the input integer ‘num’. It replaces every ‘0’ digit with ‘5’ by building a temporary integer ‘temp’ with reversed digits containing ‘5’ instead of ‘0’. It then reverses ‘temp’ to obtain the final result integer ‘reversed’ and returns it.
Example: The example below shows the replacement of all ‘0’ with ‘5’ in an input integer using the Iterative with Reversal method.
function replaceWithFive(num) {
let temp = 0;
while (num > 0) {
let digit = num % 10;
if (digit === 0) {
digit = 5;
}
temp = temp * 10 + digit;
num = Math.floor(num / 10);
}
let reversed = 0;
while (temp > 0) {
reversed = reversed * 10 + temp % 10;
temp = Math.floor(temp / 10);
}
return reversed;
}
console.log(replaceWithFive(9570320003));
Output
9575325553
Time Complexity: O(n), where n is the number of digits in the integer.
Space Complexity: O(1).
Replace all ‘0’ with ‘5’ in an Input Integer using JavaScript
Given a number, our task is to take an input integer and replace all occurrences of the digit ‘0’ with the digit ‘5’. We can solve this problem by using various methods in JavaScript.
Example:
Input:
n = 1020
Output:
1525
Below are the approaches to replace all ‘0’ with ‘5’ in an input integer using JavaScript:
Table of Content
- String Conversion and Manipulation
- Mathematical Manipulation
- Iterative with Reversal
- Recursion