In: Computer Science
BROKEN SPEEDOMETER
The cycling competition is near, so jojo needs to practice cycling. he used a speedometer found in his basement to measure his speed. however, it turns out that the speedometer is not usual! the digits on the speedometer can only count up to 2. if we add a value to a digit 2, it will revert to 0 and adds a value to the next digit.
for example, the numbers [0,1,2,3,4,5,6,7] will be shown as [0,1,2,10,11,12,20,21] on the speedometer. jojo doesn't have time to find a new speedometer, so he decided to use this one. He targets on reaching N m/s speed. help him determine what will be shown on the speedometer the moment jojo reached N m/s speed.
Format Input
The first line of input contains an integer T. the next T lines each contains an integer N, jojo's target.
Format Output
For each case, output "Case #X:Y, where X is the test case number and Y is a string denoting the numbers shown on the speedometer once jojo reached N m/s.
Constraints
. 1 ≤ T ≤ 50
. 0 ≤ N ≤ 10^5
Sample Input (standard input)
2
2
21
Sample Output (standard output)
Case #1: 2
Case #2: 210
WITH C LANGUAGE
#include <stdio.h>
int main()
{
int i,j,k,n,a[1000],l,num,temp,count=0,f=0,rem,next_num;
char str[100];
scanf("%i",&n);//inputting number of testcase
for(i=0;i<n;i++)
{
scanf("%i",&a[i]);//reading each element
}
for(i=0;i<n;i++)//loop to iterate through each array element
{
num=a[i];//stores array element at index i
count=0;/*counter that tracks if the number of new format reached */
next_num=0;/*counter that increments from 1 till the new number we search is found*/
while(count<=num)
{
temp=next_num;
f=0;/*flag to check the next_num belongs to numberof the new format i.e number in the format given n the question*/
k=temp;/*store it in the temp variable.sincevalue of temp willbe changed*/
while(temp>0)
{
rem=temp%10;
temp=temp/10;
if(rem>2)
{
f=1; /*checks if any one of the digits in the number is either 0,1,2 otherwise breaks from the loop*/
break;
}
}
if(f==0)/*if all digits are 0,1,2 then its a numberin new format*/
{
count++;/*couter increments*/
l=k;/*that number is assigned to l which is our finalnumber to be printed*/
}
next_num++;
}
printf("Case #%d: ",i+1);
sprintf(str,"%d",l);/*to convert integer to string*/
puts(str);
}
return 0;
}
The logic i have used for this program is as follows:
since it is given that after two the number will revert to 0 and added to the next number.
These are the numbers which consists of only 0,1,and 2.
for example, 21 refrers to the 21 st number starting from 1 only having 0,1,2 in them.
so i have created a for loop which iterates through each test case.
Then i have a variable next_num which will start from0 and increments by 1 in each step;
Then checks if the next_num contains just 0,1,2(number of new format). if yes count variable is incremented.
This continues till count=arrayelement