Open In App

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

Last Updated : 31 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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:

  • The function findK takes an integer N as input and initializes a variable K to 1.
  • The function enters a loop that iterates over all possible values of K from 1 to N.
  • For each value of K, the function initializes a variable sum to 0 and a variable tempK to the current value of K.
  • The function enters an inner loop that calculates the sum of the numbers formed by repeated removal of the last digit of tempK.
  • In each iteration of the inner loop, the function adds the current value of tempK to sum and updates tempK to remove its last digit by dividing it by 10.
  • The inner loop continues until tempK becomes 0.
  • After the inner loop exits, the function checks if the calculated value of sum is equal to N.
  • If sum is equal to N, the function returns the current value of K.
  • If sum is not equal to N, the function increments K and continues to the next iteration of the outer loop.
  • If no value of K is found that satisfies the given condition, the function returns -1.

C++




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


Java




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


Python3




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


C#




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


Javascript




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:

  • Consider K = 123.
  • The possible numbers formed from 123 are 1, 12, and 123.
  • Now, 123 can be expressed as 100 + 20 + 3. If all the other numbers are expressed similarly, then the idea is to know the position and frequency of each digit in all the numbers combined, to get the total sum as N
     
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
  • Now, for the given number N of length L. Divide the number with L number of 1s to get the highest place digit.
  • Calculate the remainder which will be our newly formed N.
  • Again divide the newly formed N with (L – 1) number of 1s to get 2nd highest place digit and continue till the L becomes 0.

Follow the steps below to solve the problem:

  • Let L be the count of digits in the given number N.
  • Initialize string str as L numbers of 1s in it.
  • Initialize a variable ans as zero that will store the resultant number K.
  • Iterate until the string str is not empty and follow the steps below:

ans = ans*10 + (N/M) 
 

  • Update N to N % M.
  • Remove the last character from the string str.
  • After the above steps, print the value stored in the ans which is the required value of K.

Below is the implementation of the above approach:

C++




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




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




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




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


Javascript




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



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads