Here, we will see Program to Count Number of Distinct Integers After Reverse Operations with code and algorithm.
You are given an array nums
consisting of positive integers.
You have to take each integer in the array, reverse its digits, and add it to the end of the array. You should apply this operation to the original integers in nums
.
You have to return the number of distinct integers in the final array.
Example 1:
Input: nums = [1,13,10,12,31] Output: 6 Explanation: After including the reverse of each number, the resulting array is [1,13,10,12,31,1,31,1,21,13]. The reversed integers that were added to the end of the array are highlighted. Note that for the integer 10, after reversing it, it becomes 01 which is just 1. The number of distinct integers in this array is 6 (The numbers 1, 10, 12, 13, 21, and 31).
Example 2:
Input: nums = [2,2,2] Output: 1 Explanation: After including the reverse of each number, the resulting array is [2,2,2,2,2,2]. The number of distinct integers in this array is 1 (The number 2).
Example 3:
Input: nums = [10,8,6,7,2,80] Output: 7 Explanation: After including the reverse of each number, the resulting array is [10,8,6,7,2,80,1,8,6,7,2,8]. The reversed integers that were added to the end of the array are highlighted. Note that for the integer 10 and 80, after reversing it, it becomes 01 and 08 respectively which is just 1 and 8. The number of distinct integers in this array is 7 (The numbers 10, 8, 6, 7, 2, 80, 1).
Algorithm:
- Iterate through nums array
- For each number, Reverse the number and append it to nums array
- Iterate through newly nums array
- Store number in a map to check uniqueness
- If number is not present in map then increment the counter
- Return the counter variable
Program to count number of distinct integers after reverse operations code in C++
Code 1:
#include <iostream> #include <unordered_map> #include <vector> #include <limits.h> using namespace std; int reverse_digit(int n) { int sum = 0; while(n) { sum = sum * 10 + n % 10; n /= 10; } return sum; } int countDistinctIntegers(vector<int>& nums) { unordered_map<int, bool> m; int len = nums.size(); int count = 0; for(int i = 0; i < len; i++) { int rev = reverse_digit(nums[i]); nums.push_back(rev); } for(auto it : nums) { if(m.find(it) == m.end()) { count++; m[it] = true; } } return count; } int main() { vector<int> v = {1,13,10,12,31}; cout<<countDistinctIntegers(v); return 0; }
Output:
6
To check more leetcode problem’s solution. Pls click given below link:
https://techieindoor.com/category/leetcode/