Skip to main content

Replace All 0's with 5

Problem​

You are given an integer N. You need to convert all zeroes of N to 5.

Examples:​

Example 1:

Input:
N = 1004
Output: 1554
Explanation: There are two zeroes in 1004 on replacing all zeroes with "5", the new number will be "1554".

Example 2:

Input:
N = 121
Output: 121
Explanation: Since there are no zeroes in "121", the number remains as "121".

Your task:​

Your task is to complete the function convertFive() which takes an integer N as an argument and replaces all zeros in the number N with 5. Your function should return the converted number.

  • Expected Time Complexity: O(K)O(K), where K is the number of digits in N
  • Expected Auxiliary Space: O(1)O(1)

Constraints:​

  • 1<=n<=100001 <= n <= 10000

Solution​

Python​

def convertFive(n):
n_str = str(n)
modified_digits = []
for char in n_str:
if char == '0':
modified_digits.append('5')
else:
modified_digits.append(char)
modified_str = ''.join(modified_digits)
modified_n = int(modified_str)
return modified_n

Java​

int convertfive(int num) {
String numStr = String.valueOf(num);
StringBuilder modifiedDigits = new StringBuilder();
for (int i = 0; i < numStr.length(); i++) {
char ch = numStr.charAt(i);
if (ch == '0') {
modifiedDigits.append('5');
} else {
modifiedDigits.append(ch);
}
}
int modifiednum = Integer.parseInt(modifiedDigits.toString());
return modifiednum;
}

C++​

int convertFive(int n) {
string nStr = to_string(n);
string modifiedStr = "";
for (char ch : nStr) {
if (ch == '0') {
modifiedStr += '5';
} else {
modifiedStr += ch;
}
}
int modifiedN = stoi(modifiedStr);
return modifiedN;
}

C​

int convertFive(int num) {
if (num == 0) {
return 5;
}
int result = 0;
int decimalPlace = 1;
while (num > 0) {
int digit = num % 10;
if (digit == 0) {
digit = 5;
}
result = digit * decimalPlace + result;
decimalPlace *= 10;
num /= 10;
}
return result;
}
  • Time Complexity: O(K)O(K), where K is the number of digits in N
  • Auxiliary Space: O(1)O(1)