Count unique numbers that can be generated from N by adding one and removing trailing zeros
Last Updated :
22 Jun, 2022
Given a number N. Add one to the number in the first step and if the number has trailing zeros, remove all the trailing zeros in the second step. Continue the process for the next generated number. The task is to count the number of unique numbers that can be generated from these operations.
Examples:
Input: N = 5
Output: 9
5 -> 6 -> 7 -> 8 -> 9 -> 1 -> 2 -> 3 -> 4 -> 5 (same sequence repeats)
Note that 10 is not included as it contained trailing zero
and removing the zero gave 1 as the next element.
Input: N = 28
Output: 11
Approach: The problem can be solved using recursion. Use a unordered_set to store all the unique numbers. In case a number is reached twice, we end the recursion as the same sequence will be repeated and we will not be getting any more unique numbers. Else insert the number to the set and in the first step increase the number by 1 and remove all trailing zeros in the next step if there are any.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void count_unique(unordered_set< int >& s, int n)
{
if (s.count(n))
return ;
s.insert(n);
n += 1;
while (n % 10 == 0) {
n = n / 10;
}
count_unique(s, n);
}
int main()
{
int n = 10;
unordered_set< int > s;
count_unique(s, n);
cout << s.size();
return 0;
}
|
Java
import java.util.*;
class GFG
{
static void count_unique(HashSet<Integer>s, int n)
{
if (s.contains(n))
return ;
s.add(n);
n += 1 ;
while (n % 10 == 0 )
{
n = n / 10 ;
}
count_unique(s, n);
}
public static void main(String[] args)
{
int n = 10 ;
HashSet<Integer>s = new HashSet<>();
count_unique(s, n);
System.out.println(s.size());
}
}
|
Python3
def count_unique(s, n) :
if (s.count(n)) :
return ;
s.append(n);
n + = 1 ;
while (n % 10 = = 0 ) :
n = n / / 10 ;
count_unique(s, n);
if __name__ = = "__main__" :
n = 10
s = []
count_unique(s, n)
print ( len (s))
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static void count_unique(HashSet< int >s, int n)
{
if (s.Contains(n))
return ;
s.Add(n);
n += 1;
while (n % 10 == 0)
{
n = n / 10;
}
count_unique(s, n);
}
public static void Main(String[] args)
{
int n = 10;
HashSet< int >s = new HashSet< int >();
count_unique(s, n);
Console.WriteLine(s.Count);
}
}
|
Javascript
<script>
function count_unique(s,n)
{
if (s.has(n))
return ;
s.add(n);
n += 1;
while (n % 10 == 0)
{
n = Math.floor(n / 10);
}
count_unique(s, n);
}
let n = 10;
let s = new Set();
count_unique(s, n);
document.write(s.size);
</script>
|
Time Complexity: O(9*logN), as we are using recursion in the worst case we will call the function 9 times before we decrement N by floor division of 10, which will effectively cost logN time.
Auxiliary Space: O(9*logN), as we are using extra space for the set.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...