Skip to main content

Replace All 0's with 5

Problem​

Given a number N. The task is to complete the function convertFive() which replaces all zeros in the number with 5 and returns the number.

Examples:​

Example 1:

Input
2
1004
121

Output
1554
121

Explanation:
Testcase 1: At index 1 and 2 there is 0 so we replace it with 5.
Testcase 2: There is no,0 so output will remain the same.

Input:​

The first line of input contains an integer T, denoting the number of test cases. Then T test cases follow. Each test case contains a single integer N denoting the number.

Output:​

The function will return an integer where all zero's are converted to 5.

Your task:​

Since this is a functional problem you don't have to worry about input, you just have to complete the function convertFive().

Constraints:​

  • 1<=T<=1031 <= T <= 10^3
  • 1<=N<=1041 <= N <= 10^4

Solution​

Python​

def convertFive(self,n):
num_str = str(n)
result = ""
for char in num_str:
if char == '0':
result += '5'
else:
result += char
return int(result)

Java​

public static int convertFive(int n){
String numStr = String.valueOf(n);
StringBuilder result = new StringBuilder();
for (int i = 0; i < numStr.length(); i++) {
char currentChar = numStr.charAt(i);
if (currentChar == '0') {
result.append('5');
}
else {
result.append(currentChar);
}
}
int convertedNumber = Integer.parseInt(result.toString());
return convertedNumber;
}

C++​

int convertFive(int n) {
string numStr = to_string(n);
for (char &c : numStr) {
if (c == '0') {
c = '5';
}
}
int convertedNumber = stoi(numStr);
return convertedNumber;
}

C​

int convertFive(int n) {
int result = 0;
int position = 1;
while (n != 0) {
int digit = n % 10;
if (digit == 0) {
result += 5 * position;
}
else {
result += digit * position;
}
n /= 10;
position *= 10;
}
return result;
}