TCS Digital Coding Question | August 17 2019
Question
This is the TCS Digital Coding Question asked on August 17, 2019. Given a range, find all the unique number within that range. Find the count of unique numbers and print the count.
SOLUTION 1:
#include<stdio.h> #include<stdlib.h> int main() { int a,b,tem2,rem2,tem,rem,count=0,flag,k,j,i,m; scanf("%d %d",&a,&b); int *arr = (int*)malloc(sizeof(int)*b); for(i=a; i<=b; i++) //loop for the given range { flag = 1; tem = i; k=0; while(tem) //seperate each digit in the number and store them in a array { rem = tem%10; arr[k++] = rem; tem = tem/10; } arr[k] = '\0'; tem = i; j = 0; //used keep track of index position while(tem&&flag) { rem = tem%10; for(m = 0; m<k; m++) { if(rem == arr[m]&&j!=m) //element is found in the array and { // it not same index Ex: duplicate element flag = 0; break; } } j++; //increase index count tem = tem/10; } if(flag) //if flag == 1 count++; //increase count of unique number } printf("%d",count); //total count of unique number return 0; }
SOLUTION 2 (using Hashing)
In this we store the count of each digit in a array using hashing. For example num = 133 then count[1] =1, count[3] =2.
#include<stdio.h> int main() { int i,a,flag,j,b,tem,rem,total=0; int count[10]={0}; scanf("%d %d",&a,&b); for(i = a; i<=b; i++) //loop for the given range { tem = i; flag =1; while(tem) { rem = tem %10; count[rem] +=1; //increase the count of rem Ex: if rem=2 then count[2]++ tem = tem/10; } for(j = 0;j<10; j++) //loop from 0 to 9 { //any digit have count more than 1 EX: 1222 then count[2]=>3 which is greater than 1 if(count[j]>1) { flag = 0; break; } } if(flag) { total++; printf("%d ",i); } //increase the count of unique number /*Reset the count of digits to 0 */ for(j=0;j<10;j++) { count[j] = 0; } } printf("%d ",total); }
SOLUTION 3: (Using Set)
In this, we use Set to check whether the duplicate element is present or not because Set can hold only unique elements.
import java.util.Scanner; import java.util.Set; import java.util.HashSet; public class TCSdigital { public static void main(String ar[]) { Scanner sc = new Scanner(System.in); int a = sc.nextInt(); int b = sc.nextInt(); boolean flag = true; int count=0,tem,rem; /*Set is the check whether duplicate digit is present * cuz set can store only unique elements */ Set<Integer> s = new HashSet<Integer>(); for(int i = a; i<=b; i++) { tem = i; flag = true; while(tem!= 0) { rem = tem%10; //s.add() returns false if it is a duplicate element if(!(s.add(rem))) { flag = false; break; } tem = tem/10; } if(flag) count++; s.clear(); //clear the set so that the next number in the range can be stored } System.out.println(count); } }
YOU MIGHT ALSO LIKE…
TCS NQT 2020 | Day 1 |Set 4
TCS NQT 2020 | Day 1 | Set 1
Want to launch your own website?
visit: 2D Technologies – Launch website and digital marketing
Use promo code: “wisdomoverflow” and get 50% off. Limited Period offer!