![]() |
VOOZH | about |
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.
: 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.
:
Implementation:
15125
Complexity Analysis:
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:
Implementation:
1525
Complexity Analysis:
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:
Implementation:
15125
Complexity Analysis:
Approach (Using builtin function replace())
15125
Time Complexity: O(log(num)), where num is the number of digits in num variable.
Auxiliary Space: O(num)