Replace all ‘0’ with ‘5’ in an input Integer
Last Updated :
23 Jul, 2025
Given an integer as input and replace all the ‘0’ with ‘5’ in the integer.
Examples:
Input: 102
Output: 152
Explanation: All the digits which are '0' is replaced by '5'
Input: 1020
Output: 1525
Explanation: All the digits which are '0' is replaced by '5'
The use of an array to store all digits is not allowed.
Iterative Approach-1: By observing the test cases it is evident that all the 0 digits are replaced by 5. For Example, for input = 1020, output = 1525. The idea is simple, we assign a variable 'temp' to 0, we get the last digit using mod operator '%'. If the digit is 0, we replace it with 5, otherwise, keep it as it is. Then we multiply the 'temp' with 10 and add the digit got by mod operation. After that, we divide the original number by 10 to get the other digits. In this way, we will have a number in which all the '0's are assigned with '5's. If we reverse this number, we will get the desired answer.
Algorithm:
- if the number is 0, directly return 5.
- else do the steps below.
- Create a variable temp= 0 to store the reversed number having all '0's assigned to '5's.
- Find the last digit using the mod operator '%'. If the digit is '0', then make the last digit '5'.
- Multiply temp with 10 and add the last digit.
- Divide the number by 10 to get more digits by mod operation.
- Then reverse this number.
- return the reversed number.
Implementation:
C++
// C++ program to replace all ‘0’
// with ‘5’ in an input Integer
#include <iostream>
using namespace std;
// A iterative function to reverse a number
int reverseTheNumber(int temp)
{
int ans = 0;
while (temp > 0) {
int rem = temp % 10;
ans = ans * 10 + rem;
temp = temp / 10;
}
return ans;
}
int convert0To5(int num)
{
// if num is 0 return 5
if (num == 0)
return 5;
// Extract the last digit and
// change it if needed
else {
int temp = 0;
while (num > 0) {
int digit = num % 10;
//if digit is 0, make it 5
if (digit == 0)
digit = 5;
temp = temp * 10 + digit;
num = num / 10;
}
// call the function reverseTheNumber by passing
// temp
return reverseTheNumber(temp);
}
}
// Driver code
int main()
{
int num = 10120;
cout << convert0To5(num);
return 0;
}
// This code is contributed by Vrashank Rao M.
Java
// Java program for the above approach
import java.io.*;
class GFG {
// A iterative function to reverse a number
static int reverseTheNumber(int temp)
{
int ans = 0;
while (temp > 0) {
int rem = temp % 10;
ans = ans * 10 + rem;
temp = temp / 10;
}
return ans;
}
static int convert0To5(int num)
{
// if num is 0 return 5
if (num == 0)
return 5;
// Extract the last digit and
// change it if needed
else {
int temp = 0;
while (num > 0) {
int digit = num % 10;
//if digit is 0, make it 5
if (digit == 0)
digit = 5;
temp = temp * 10 + digit;
num = num / 10;
}
// call the function reverseTheNumber by passing
// temp
return reverseTheNumber(temp);
}
}
// Driver program
public static void main(String args[])
{
int num = 10120;
System.out.println(convert0To5(num));
}
}
// This code is contributed by sanjoy_62.
Python3
# Python program for the above approach
# A iterative function to reverse a number
def reverseTheNumber(temp):
ans = 0;
while (temp > 0):
rem = temp % 10;
ans = ans * 10 + rem;
temp = temp // 10;
return ans;
def convert0To5(num):
# if num is 0 return 5
if (num == 0):
return 5;
# Extract the last digit and
# change it if needed
else:
temp = 0;
while (num > 0):
digit = num % 10;
# if digit is 0, make it 5
if (digit == 0):
digit = 5;
temp = temp * 10 + digit;
num = num // 10;
# call the function reverseTheNumber by passing
# temp
return reverseTheNumber(temp);
# Driver program
if __name__ == '__main__':
num = 10120;
print(convert0To5(num));
# This code is contributed by umadevi9616
C#
// C# program for the above approach
using System;
public class GFG {
// A iterative function to reverse a number
static int reverseTheNumber(int temp)
{
int ans = 0;
while (temp > 0) {
int rem = temp % 10;
ans = ans * 10 + rem;
temp = temp / 10;
}
return ans;
}
static int convert0To5(int num)
{
// if num is 0 return 5
if (num == 0)
return 5;
// Extract the last digit and
// change it if needed
else {
int temp = 0;
while (num > 0) {
int digit = num % 10;
//if digit is 0, make it 5
if (digit == 0)
digit = 5;
temp = temp * 10 + digit;
num = num / 10;
}
// call the function reverseTheNumber by passing
// temp
return reverseTheNumber(temp);
}
}
// Driver Code
public static void Main (string[] args) {
int num = 10120;
Console.Write(convert0To5(num));
}
}
// This code is contributed by splevel62.
JavaScript
<script>
// javascript program for the above approach
// A iterative function to reverse a number
function reverseTheNumber(temp) {
var ans = 0;
while (temp > 0) {
var rem = temp % 10;
ans = ans * 10 + rem;
temp = parseInt(temp / 10);
}
return ans;
}
function convert0To5(num)
{
// if num is 0 return 5
if (num == 0)
return 5;
// Extract the last digit and
// change it if needed
else {
var temp = 0;
while (num > 0) {
var digit = num % 10;
// if digit is 0, make it 5
if (digit == 0)
digit = 5;
temp = temp * 10 + digit;
num = parseInt(num / 10);
}
// call the function reverseTheNumber by passing
// temp
return reverseTheNumber(temp);
}
}
// Driver program
var num = 10120;
document.write(convert0To5(num));
// This code is contributed by umadevi9616
</script>
Complexity Analysis:
- Time Complexity: O(n), where n is number of digits in the number.
- Auxiliary Space: O(1), no extra space is required.
Iterative Approach-2: By observing the test cases it is evident that all the 0 digits are replaced by 5. For Example, for input = 1020, output = 1525, which can be written as 1020 + 505, which can be further written as 1020 + 5*(10^2) + 5*(10^0). So the solution can be formed in an iterative way where if a '0' digit is encountered find the place value of that digit and multiply it with 5 and find the sum for all 0's in the number. Add that sum to the input number to find the output number.
Algorithm:
- Create a variable sum = 0 to store the sum, place = 1 to store the place value of the current digit, and create a copy of the input variable
- If the number is zero return 5
- Iterate the next step while the input variable is greater than 0
- Extract the last digit (n%10) and if the digit is zero, then update sum = sum + place*5, remove the last digit from the number n = n/10 and update place = place * 10
- Return the sum.
Implementation:
C++
#include<bits/stdc++.h>
using namespace std;
// Returns the number to be added to the
// input to replace all zeroes with five
int calculateAddedValue(int number)
{
// Amount to be added
int result = 0;
// Unit decimal place
int decimalPlace = 1;
if (number == 0)
{
result += (5 * decimalPlace);
}
while (number > 0)
{
if (number % 10 == 0)
{
// A number divisible by 10, then
// this is a zero occurrence in
// the input
result += (5 * decimalPlace);
}
// Move one decimal place
number /= 10;
decimalPlace *= 10;
}
return result;
}
int replace0with5(int number)
{
return number += calculateAddedValue(number);
}
// Driver code
int main()
{
cout << replace0with5(1020);
}
// This code is contributed by avanitrachhadiya2155
Java
import java.io.*;
public class ReplaceDigits {
static int replace0with5(int number)
{
return number += calculateAddedValue(number);
}
// returns the number to be added to the
// input to replace all zeroes with five
private static int calculateAddedValue(int number)
{
// amount to be added
int result = 0;
// unit decimal place
int decimalPlace = 1;
if (number == 0) {
result += (5 * decimalPlace);
}
while (number > 0) {
if (number % 10 == 0)
// a number divisible by 10, then
// this is a zero occurrence in the input
result += (5 * decimalPlace);
// move one decimal place
number /= 10;
decimalPlace *= 10;
}
return result;
}
public static void main(String[] args)
{
System.out.print(replace0with5(1020));
}
}
Python3
def replace0with5(number):
number += calculateAddedValue(number)
return number
# returns the number to be added to the
# input to replace all zeroes with five
def calculateAddedValue(number):
# amount to be added
result = 0
# unit decimal place
decimalPlace = 1
if (number == 0):
result += (5 * decimalPlace)
while (number > 0):
if (number % 10 == 0):
# a number divisible by 10, then
# this is a zero occurrence in the input
result += (5 * decimalPlace)
# move one decimal place
number //= 10
decimalPlace *= 10
return result
# Driver code
print(replace0with5(1020))
# This code is contributed by shubhmasingh10
C#
using System;
class GFG{
static int replace0with5(int number)
{
return number += calculateAddedValue(number);
}
// Returns the number to be added to the
// input to replace all zeroes with five
static int calculateAddedValue(int number)
{
// Amount to be added
int result = 0;
// Unit decimal place
int decimalPlace = 1;
if (number == 0)
{
result += (5 * decimalPlace);
}
while (number > 0)
{
if (number % 10 == 0)
// A number divisible by 10, then
// this is a zero occurrence in the input
result += (5 * decimalPlace);
// Move one decimal place
number /= 10;
decimalPlace *= 10;
}
return result;
}
// Driver Code
static public void Main()
{
Console.WriteLine(replace0with5(1020));
}
}
// This code is contributed by rag2127
JavaScript
<script>
// Returns the number to be added to the
// input to replace all zeroes with five
function calculateAddedValue(number){
// Amount to be added
let result = 0;
// Unit decimal place
let decimalPlace = 1;
if (number == 0) {
result += (5 * decimalPlace);
}
while (number > 0){
if (number % 10 == 0){
// A number divisible by 10, then
// this is a zero occurrence in
// the input
result += (5 * decimalPlace);
}
// Move one decimal place
number = Math.floor(number/10);
decimalPlace *= 10;
}
return result;
}
function replace0with5(number){
return number += calculateAddedValue(number);
}
// Driver code
document.write(replace0with5(1020));
</script>
Complexity Analysis:
- Time Complexity: O(k), the loops run only k times, where k is the number of digits of the number.
- Auxiliary Space: O(1), no extra space is required.
Recursive Approach: The idea is simple, we get the last digit using the mod operator '%'. If the digit is 0, we replace it with 5, otherwise, keep it as it is. Then we recur for the remaining digits. The approach remains the same, the basic difference is the loop is replaced by a recursive function.
Algorithm:
- Check a base case when the number is 0 return 5, and for all other cases, form a recursive function.
- The function (solve(int n))can be defined as follows, if the number passed is 0 then return 0, else extract the last digit i.e. n = n/10 and remove the last digit. If the last digit is zero assigns 5 to it.
- Now return the value by calling the recursive function for n, i.e return solve(n)*10 + digit.
- Print the answer.
Implementation:
C++
// C++ program to replace all ‘0’
// with ‘5’ in an input Integer
#include <bits/stdc++.h>
using namespace std;
// A recursive function to replace all 0s
// with 5s in an input number It doesn't
// work if input number itself is 0.
int convert0To5Rec(int num)
{
// Base case for recursion termination
if (num == 0)
return 0;
// Extract the last digit and
// change it if needed
int digit = num % 10;
if (digit == 0)
digit = 5;
// Convert remaining digits and
// append the last digit
return convert0To5Rec(num / 10) * 10 + digit;
}
// It handles 0 and calls convert0To5Rec()
// for other numbers
int convert0To5(int num)
{
if (num == 0)
return 5;
else
return convert0To5Rec(num);
}
// Driver code
int main()
{
int num = 10120;
cout << convert0To5(num);
return 0;
}
// This code is contributed by Code_Mech.
C
// C program to replace all ‘0’
// with ‘5’ in an input Integer
#include <stdio.h>
// A recursive function to replace
// all 0s with 5s in an input number
// It doesn't work if input number itself is 0.
int convert0To5Rec(int num)
{
// Base case for recursion termination
if (num == 0)
return 0;
// Extract the last digit and change it if needed
int digit = num % 10;
if (digit == 0)
digit = 5;
// Convert remaining digits
// and append the last digit
return convert0To5Rec(num / 10) * 10 + digit;
}
// It handles 0 and calls
// convert0To5Rec() for other numbers
int convert0To5(int num)
{
if (num == 0)
return 5;
else
return convert0To5Rec(num);
}
// Driver program to test above function
int main()
{
int num = 10120;
printf("%d", convert0To5(num));
return 0;
}
Java
import java.io.*;
// Java code for Replace all 0 with
// 5 in an input Integer
public class GFG {
// A recursive function to replace all 0s with 5s in
// an input number. It doesn't work if input number
// itself is 0.
static int convert0To5Rec(int num)
{
// Base case
if (num == 0)
return 0;
// Extract the last digit and change it if needed
int digit = num % 10;
if (digit == 0)
digit = 5;
// Convert remaining digits and append the
// last digit
return convert0To5Rec(num / 10) * 10 + digit;
}
// It handles 0 and calls convert0To5Rec() for
// other numbers
static int convert0To5(int num)
{
if (num == 0)
return 5;
else
return convert0To5Rec(num);
}
// Driver function
public static void main(String[] args)
{
System.out.println(convert0To5(10120));
}
}
// This code is contributed by Kamal Rawal
Python3
# Python program to replace all
# 0 with 5 in given integer
# A recursive function to replace all 0s
# with 5s in an integer
# Does'nt work if the given number is 0 itself
def convert0to5rec(num):
# Base case for recursion termination
if num == 0:
return 0
# Extract the last digit and change it if needed
digit = num % 10
if digit == 0:
digit = 5
# Convert remaining digits and append the last digit
return convert0to5rec(num // 10) * 10 + digit
# It handles 0 to 5 calls convert0to5rec()
# for other numbers
def convert0to5(num):
if num == 0:
return 5
else:
return convert0to5rec(num)
# Driver Program
num = 10120
print (convert0to5(num))
# Contributed by Harshit Agrawal
C#
// C# code for Replace all 0
// with 5 in an input Integer
using System;
class GFG {
// A recursive function to replace
// all 0s with 5s in an input number.
// It doesn't work if input number
// itself is 0.
static int convert0To5Rec(int num)
{
// Base case
if (num == 0)
return 0;
// Extract the last digit and
// change it if needed
int digit = num % 10;
if (digit == 0)
digit = 5;
// Convert remaining digits
// and append the last digit
return convert0To5Rec(num / 10) * 10 + digit;
}
// It handles 0 and calls
// convert0To5Rec() for other numbers
static int convert0To5(int num)
{
if (num == 0)
return 5;
else
return convert0To5Rec(num);
}
// Driver Code
static public void Main()
{
Console.Write(convert0To5(10120));
}
}
// This code is contributed by Raj
PHP
<?php
// PHP program to replace all 0 with 5
// in given integer
// A recursive function to replace all 0s
// with 5s in an integer. Does'nt work if
// the given number is 0 itself
function convert0to5rec($num)
{
// Base case for recursion termination
if ($num == 0)
return 0;
// Extract the last digit and
// change it if needed
$digit = ($num % 10);
if ($digit == 0)
$digit = 5;
// Convert remaining digits and append
// the last digit
return convert0to5rec((int)($num / 10)) *
10 + $digit;
}
// It handles 0 to 5 calls convert0to5rec()
// for other numbers
function convert0to5($num)
{
if ($num == 0)
return 5;
else
return convert0to5rec($num);
}
// Driver Code
$num = 10120;
print(convert0to5($num));
// This code is contributed by mits
?>
JavaScript
<script>
// javascript code for Replace all 0 with
// 5 in an input Integer
// A recursive function to replace all 0s with 5s in
// an input number. It doesn't work if input number
// itself is 0.
function convert0To5Rec(num) {
// Base case
if (num == 0)
return 0;
// Extract the last digit and change it if needed
var digit = num % 10;
if (digit == 0)
digit = 5;
// Convert remaining digits and append the
// last digit
return convert0To5Rec(parseInt(num / 10)) * 10 + digit;
}
// It handles 0 and calls convert0To5Rec() for
// other numbers
function convert0To5(num) {
if (num == 0)
return 5;
else
return convert0To5Rec(num);
}
// Driver function
document.write(convert0To5(10120));
// This code contributed by gauravrajput1
</script>
Complexity Analysis:
- Time Complexity: O(k), the recursive function is called only k times, where k is the number of digits of the number
- Auxiliary Space: O(1), no extra space is required.
Approach (Using builtin function replace())
C++
#include <bits/stdc++.h>
using namespace std;
string change(int n)
{
string temp = to_string(n) + "";
replace(temp.begin(), temp.end(), '0', '5');
return temp;
}
int main()
{
int num = 10120;
cout << (change(num));
return 0;
}
// This code is contributed by akashish__
Java
/*package whatever //do not write package name here */
import java.io.*;
class GFG {
static String change(int n){
String temp = n + "";
return temp.replace('0','5');
}
public static void main (String[] args) {
int num = 10120;
System.out.println(change(num));
}
}
// This code is contributed by aadityaburujwale.
Python3
# Python program for the above approach
# Function to replace all 0s with 5s
def change(num):
s = str(num)
s = s.replace('0', '5')
return s
# Driver code
if __name__ == '__main__':
num = 10120
print(change(num))
C#
using System;
public class GFG {
static String change(int n)
{
String temp = n + "";
return temp.Replace('0', '5');
}
static public void Main()
{
// Code
int num = 10120;
Console.WriteLine(change(num));
}
}
// This code is contributed by karandeep1234
JavaScript
function change(n)
{
let temp = n.toString();
temp = temp.replaceAll('0', '5');
return temp;
}
let num = 10120;
console.log((change(num)));
// This code is contributed by akashish__
Time Complexity: O(log(num)), where num is the number of digits in num variable.
Auxiliary Space: O(num)
Replace all 0's with 5 | DSA Practice Problem
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem