Replace all ‘0’ with ‘5’ in an input Integer

Given an integer as input and replace all the ‘0’ with ‘5’ in the integer.
Examples:

Input: 102 
Output: 152

Explantion: All the digits which are '0' is replaced by '5' 

Input: 1020 
Output: 1525

Explantion: All the digits which are '0' is replaced by '5' 

Use of array to store all digits is not allowed.

Source: Amazon interview Experience | Set 136 (For SDE-T)



Iterative Approach: 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:
    1. Create a variable sum = 0 to store the sum, place = 1 to store the place value of current digit and create a copy of input variable
    2. If the number is zero return 5
    3. Iterate the next step while the input variable is greater than 0
    4. Extract the last digit (n%10) and if the digit is zero, then update sum = sum + place*5, remove the last digit from the numbern = n/10 and update place = place * 10
    5. Return the sum.
  • Implementation:

    Java

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    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));
        }
    }

    chevron_right

    
    

    Python3

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    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

    chevron_right

    
    

  • Output:
    1525
  • Complexity Analysis:
    • Time Complexity:O(k), the loops runs only k times, where k is the number of digits of the number.
    • Space Complexity:O(1), no extra space is required.
  • Recursive Approach: The idea is simple, 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 recur for remaining digits. The approach remains the same, the basic difference is the loop is replaced by a recursive function.

    • Algorithm:
      1. Check a base case when the number is 0 return 5, for all other cases form a recursive function.
      2. 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 the assign 5 to it.
      3. Now return the value by calling the recursive function for n ,i.e return solve(n)*10 + digit
      4. print the answer.
    • Implementation:

      C++

      filter_none

      edit
      close

      play_arrow

      link
      brightness_4
      code

      // 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;
        
          // Extraxt 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.

      chevron_right

      
      

      C

      filter_none

      edit
      close

      play_arrow

      link
      brightness_4
      code

      // 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;
        
          // Extraxt 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;
      }

      chevron_right

      
      

      Java

      filter_none

      edit
      close

      play_arrow

      link
      brightness_4
      code

      // Java code for Replace all 0 with 5 in an input Integer
      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;
        
              // Extraxt 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

      chevron_right

      
      

      Python

      filter_none

      edit
      close

      play_arrow

      link
      brightness_4
      code

      # 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 recurssion 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

      chevron_right

      
      

      C#

      filter_none

      edit
      close

      play_arrow

      link
      brightness_4
      code

      // 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;
        
              // Extraxt 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

      chevron_right

      
      

      PHP

      filter_none

      edit
      close

      play_arrow

      link
      brightness_4
      code

      <?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 recurssion 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
      ?>

      chevron_right

      
      


      Output:

      15125

      Complexity Analysis:

    • Time Complexity:O(k), the recusrsive function is called only k times, where k is the number of digits of the number
    • Space Complexity:O(1), no extra space is required.
    • This article is contributed by Sai Kiran. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.




      My Personal Notes arrow_drop_up