Open In App

Find a number K having sum of numbers obtained by repeated removal of last digit of K is N

Given an integer N, the task is to find an integer K such that the sum of the numbers formed by repeated removal of the last digit of K is equal to N.

Examples:



Input: N = 136
Output: 123
Explanation: 
 



The numbers formed by repeatedly removing the last digit of 123 are {123, 12, 1}.
Therefore, the sum of these numbers = 123 + 12 + 1 = 136( = N).

Input: N = 107
Output: 98
Explanation:
The numbers formed by repeatedly removing the last digit of 98 are {98, 9}.
Therefore, the sum of these numbers = 98 + 7 = 107( = N).

Naive approach:

 Here’s a step-by-step explanation of the brute-force approach to solving this problem:




#include <iostream>
using namespace std;
 
int findK(int N) {
    for (int K = 1; K <= N; K++) {
        int sum = 0;
        int tempK = K;
        while (tempK > 0) {
            sum += tempK;
            tempK /= 10;
        }
        if (sum == N) {
            return K;
        }
    }
    return -1;
}
 
int main() {
    int N = 136;
    cout << findK(N);
    return 0;
}




public class GFG {
    public static int findK(int N)
    {
        for (int K = 1; K <= N; K++) {
            int sum = 0;
            int tempK = K;
            while (tempK > 0) {
                sum += tempK;
                tempK /= 10;
            }
            if (sum == N) {
                return K;
            }
        }
        return -1;
    }
 
    public static void main(String[] args)
    {
        int N = 136;
        System.out.println(findK(N));
    }
}




def findK(N):
    for K in range(1, N + 1):
        sum = 0
        tempK = K
        while tempK > 0:
            sum += tempK
            tempK //= 10
        if sum == N:
            return K
    return -1
 
N = 136
print(findK(N))
 
 
# This code is contributed by shivamgupta310570




using System;
 
public class GFG
{
    public static int FindK(int N)
    {
        for (int K = 1; K <= N; K++)
        {
            int sum = 0;
            int tempK = K;
 
            // Calculate the sum of digits in K
            while (tempK > 0)
            {
                sum += tempK ;
                tempK /= 10;
            }
 
            // Check if the sum of digits equals N
            if (sum == N)
            {
                return K;
            }
        }
 
        // If no such K is found, return -1
        return -1;
    }
 
    public static void Main(string[] args)
    {
        int N = 136;
        Console.WriteLine(FindK(N));
    }
}
 
 
// This code is contributed by shivamgupta0987654321




class GFG {
    static findK(N) {
        for (let K = 1; K <= N; K++) {
            let sum = 0;
            let tempK = K;
            while (tempK > 0) {
                sum += tempK;
                tempK = Math.floor(tempK / 10);
            }
            if (sum === N) {
                return K;
            }
        }
        return -1;
    }
}
 
const N = 136;
console.log(GFG.findK(N));

Output
123








Time Complexity: O(N*log(N)), where N is the input value. This is because in the worst case, the outer loop iterates N times and the inner loop iterates log(N) times for each iteration of the outer loop.
Auxiliary Space: O(1), as it uses a constant amount of additional space to store variables such as K, sum, and tempK.

Efficient Approach: The approach is based on the following observations:

Digit Frequency of each digit Sum
units tens hundreds
1 1 1 1 1*1 + 1*10 + 1*100 = 111
2 1 1   2*1 + 2*10 = 22
3 1     3*1 = 3

Follow the steps below to solve the problem:

ans = ans*10 + (N/M) 
 

Below is the implementation of the above approach:




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the value of K
int findK(int N, int l)
{
    // Stores l number of 1s
    string ones = "";
 
    while (l--) {
 
        // Storing 1's
        ones = ones + '1';
    }
 
    // Stores the value of K
    int ans = 0;
 
    // Iterate until ones is empty
    while (ones != "") {
 
        // Convert ones to number
        int m = stoi(ones);
 
        // Update the ans
        ans = (ans * 10) + (N / m);
 
        // Update N to N%m
        N = N % m;
 
        // Removing last digit from ones
        ones.pop_back();
    }
 
    // Return the value of K
    return ans;
}
 
// Driver Code
int main()
{
    // Given number N
    int N = 136;
 
    // Number of digits in N
    int L = to_string(N).length();
 
    // Function Call
    cout << findK(N, L);
 
    return 0;
}




// Java program for
// the above approach
import java.util.*;
class GFG{
 
// Function to find the
// value of K
static int findK(int N,
                 int l)
{
  // Stores l number of 1s
  String ones = "";
 
  while (l-- > 0)
  {
    // Storing 1's
    ones += '1';
  }
 
  // Stores the value of K
  int ans = 0;
 
  // Iterate until ones is empty
  while (!ones.equals(""))
  {
    // Convert ones to number
    int m = Integer.valueOf(ones);
 
    // Update the ans
    ans = (ans * 10) + (N / m);
 
    // Update N to N%m
    N = N % m;
 
    // Removing last digit from ones
    ones = ones.substring(0,
           ones.length() - 1);
  }
 
  // Return the value of K
  return ans;
}
 
// Driver Code
public static void main(String[] args)
{
  // Given number N
  int N = 136;
 
  // Number of digits in N
  int L = String.valueOf(N).length();
 
  // Function Call
  System.out.print(findK(N, L));
}
}
 
// This code is contributed by 29AjayKumar




# Python3 program for
# the above approach
 
# Function to find
# the value of K
def findK(N, l):
 
    # Stores l number of 1s
    ones = ""
 
    while (l):
 
        #  Storing 1's
        ones = ones + '1'
        l -= 1
    
    # Stores the value of K
    ans = 0
     
    # Iterate until ones
    # is empty
    while (ones != ""):
 
        # Convert ones to number
        m = int(ones)
 
        # Update the ans
        ans = (ans * 10) + (N // m)
 
        # Update N to N%m
        N = N % m
 
        # Removing last digit from ones
        ones = ones.replace(ones[-1], "", 1)
     
    # Return the value of K
    return ans
 
# Driver Code
if __name__ == "__main__":
   
    # Given number N
    N = 136
 
    # Number of digits in N
    L = len(str(N))
 
    # Function Call
    print (findK(N, L))
 
# This code is contributed by Chitranayal




// C# program for
// the above approach
using System;
class GFG{
 
// Function to find the
// value of K
static int findK(int N,
                 int l)
{
  // Stores l number of 1s
  String ones = "";
 
  while (l-- > 0)
  {
    // Storing 1's
    ones += '1';
  }
 
  // Stores the value of K
  int ans = 0;
 
  // Iterate until ones is empty
  while (!ones.Equals(""))
  {
    // Convert ones to number
    int m = Int32.Parse(ones);
 
    // Update the ans
    ans = (ans * 10) + (N / m);
 
    // Update N to N%m
    N = N % m;
 
    // Removing last digit from ones
    ones = ones.Substring(0,
           ones.Length - 1);
  }
 
  // Return the value of K
  return ans;
}
 
// Driver Code
public static void Main(String[] args)
{
  // Given number N
  int N = 136;
 
  // Number of digits in N
  int L = String.Join("", N).Length;
 
  // Function Call
  Console.Write(findK(N, L));
}
}
 
// This code is contributed by Princi Singh




<script>
 
      // JavaScript program for
      // the above approach
      // Function to find the
      // value of K
      function findK(N, l) {
        // Stores l number of 1s
        var ones = "";
 
        while (l) {
          // Storing 1's
          ones += "1";
          l -= 1;
        }
 
        // Stores the value of K
        var ans = 0;
 
        // Iterate until ones is empty
        while (ones !== "") {
          // Convert ones to number
          var m = parseInt(ones);
 
          // Update the ans
          ans = parseInt(ans * 10 + N / m);
 
          // Update N to N%m
          N = N % m;
 
          // Removing last digit from ones
          ones = ones.substring(0, ones.length - 1);
        }
 
        // Return the value of K
        return ans;
      }
 
      // Driver Code
      // Given number N
      var N = 136;
 
      // Number of digits in N
      var L = N.toString().length;
 
      // Function Call
      document.write(findK(N, L));
       
</script>

Output
123








Time Complexity: O(log10N)
Auxiliary Space: O(1)


Article Tags :