
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Count Unique Numbers by Adding One and Removing Trailing Zeros in C++
We are given a number N as input. Perform two operations on N and identify the count of unique numbers generated in the process. Steps will −
Add 1 to number
Remove trailing zeros from the generated number, if any
If N is 8 then numbers generated will be
Applying step 1− 8 → 9 →
Applying step 2− 1 → ( removed 0 from 10 )
Applying step 1: 2 → 3 → 4 → 5 → 6 → 7 → 8 ( same sequence )
Count of unique numbers will be 9.
For Example
Input
N=21
Output
Count of unique numbers that can be generated from N by adding one and removing trailing zeros are: 18
Explanation
Numbers will be: 21, 22, 23, 24, 25, 26, 27, 28, 29, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3 −−−now same sequence Unique numbers are: 18
Input
N=38
Output
Count of unique numbers that can be generated from N by adding one and removing trailing zeros are: 11
Explanation
Numbers will be: 38, 39, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4 −−−now same sequence Unique numbers are: 11
Approach used in the below program is as follows −
In this approach we will create an unordered set which will contain all unique numbers generated after applying steps 1 and 2. In case the numbers repeat, then we will stop the iteration. The size of the set will give us the count of unique numbers generated in the process.
Take the number N as integer.
Take the unordered_set<int> U_S for inserting generated numbers.
Function unique_N(unordered_set<int>& U_S, int N) takes the set and N and adds numbers to the set U_S until all numbers are unique in it.
If U_S.count(N) returns 1 that means N already exists in the set. So the numbers would repeat, return from the function.
Otherwise insert N to the set and apply operation 1 ( increment by 1).
Check if number N has trailing zeroes (is multiple of 10).
If N % 10 is 0, then remove trailing zero by dividing it by 10.
Call function unique_N() with updated N.
After returning from the function, take count as the size of the set U_S.
Print result as count.
Example
#include <bits/stdc++.h> using namespace std; void unique_N(unordered_set<int>& U_S, int N){ if (U_S.count(N)){ return; } U_S.insert(N); N = N + 1; while (N % 10 == 0){ N = N / 10; } unique_N(U_S, N); } int main(){ int N = 7; unordered_set<int> U_S; unique_N(U_S, N); int count = U_S.size(); cout<<"Count of unique numbers that can be generated from N by adding one and removing trailing zeros are: "<<count; return 0; }
Output
If we run the above code it will generate the following output −
Count of unique numbers that can be generated from N by adding one and removing trailing zeros are: 9